MySQL多个连接而不组合到同一行

时间:2014-08-27 06:24:07

标签: mysql join

我有五个表格如下,最后的结果集我想退出查询,其中每一行都是c1 c2之一的一个ID }或c3个表格,以及相应的ab个ID。

我目前正在尝试的查询以及我目前得到的结果集已经结束。

一个

+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
+----+

B'/强>

+----+------+
| id | a_id |
+----+------+
|  1 |    1 |
|  2 |    1 |
|  3 |    2 |
+----+------+

C1

+-----+------+
| id  | b_id |
+-----+------+
| c11 |    1 |
| c12 |    2 |
+-----+------+

C2

+-----+------+
| id  | b_id |
+-----+------+
| c21 |    1 |
| c22 |    3 |
+-----+------+

C3

+-----+------+
| id  | b_id |
+-----+------+
| c31 |    2 |
| c32 |    3 |
+-----+------+

所需的查询结果

+----+------+-------+-------+-------+
| id | b_id | c1_id | c2_id | c3_id |
+----+------+-------+-------+-------+
|  1 |    1 | c11   |       |       |
|  1 |    2 | c12   |       |       |
|  1 |    1 |       | c21   |       |
|  2 |    3 |       | c22   |       |
|  1 |    2 |       |       | c31   |
|  2 |    3 |       |       | c32   |
+----+------+-------+-------+-------+

查询

SELECT a.id, b.id, c1.id, c2.id, c3.id
FROM a
INNER JOIN b ON b.a_id = a.id
LEFT JOIN c1 ON c1.b_id = b.id
LEFT JOIN c2 ON c2.b_id = b.id
LEFT JOIN c3 ON c3.b_id = b.id

实际结果

+----+------+-------+-------+-------+
| id | b_id | c1_id | c2_id | c3_id |
+----+------+-------+-------+-------+
|  1 |    1 | c11   | c21   |       |
|  1 |    2 | c12   |       | c31   |
|  2 |    3 |       | c22   | c32   |
+----+------+-------+-------+-------+

1 个答案:

答案 0 :(得分:2)

试试这个希望它对你有用

 (
   SELECT a.id, b.id, c1.id as c1id, "" as c2id, "" as c3id
   FROM a
   INNER JOIN b ON b.a_id = a.id
   INNER JOIN c1 ON c1.b_id = b.id
 ) 
 union 
 (
   SELECT a.id, b.id,"" as c1id, c2.id as c2id, "" as c3id
   FROM a
   INNER JOIN b ON b.a_id = a.id
   INNER JOIN c2 ON c2.b_id = b.id
 ) 
 union 
 (
   SELECT a.id, b.id,"" as c1id,"" as c2id, c3.id as c3id
   FROM a
   INNER JOIN b ON b.a_id = a.id
   INNER JOIN c3 ON c3.b_id = b.id
 )