2016-07-29 64 views
0

我有3個表table1的列id1有三個值'1','2','3',table2的列id2有三個值'3','4', '5'和table3的列id3具有三個值'5','6','7'我如何加入所有這三個表,並且我還希望null值被顯示.pls通過下面的示例。連接3個包含空值的表

table1  |  table2  |  table3 
---------------------------------------------------- 
id1   |  id2   |  id3 
---------------------------------------------------- 
    1   |  3   |  5 
    2   |  4   |  6 
    3   |  5   |  7 

這是我所期望的輸出是

id1 | id2 | id3 
---------------------- 
1 | null | null 
2 | null | null 
3 | 3 | null 
null | 4 | null 
null | 5 | 5 
null | null | 6 
null | null | 7 

some1請你幫我感到困惑

+1

MySQL是否支持FULL OUTER JOIN? – jarlh

回答

1

你需要一個完整的外部聯接,遺憾的是,MySQL沒有全外連接。有一個request,但它仍然是開放的。

你有幾個左側之間做工會模仿他們加入,循環:

SELECT id1, id2, id3 
FROM 
    table1 
    LEFT JOIN table2 on table1.id1 = table2.id2 
    LEFT JOIN table3 on table2.id2 = table3.id3 
UNION 
SELECT id1, id2, id3 
FROM 
    table2 
    LEFT JOIN table3 on table2.id2 = table3.id3 
    LEFT JOIN table1 on table3.id3 = table1.id1 
UNION 
SELECT id1, id2, id3 
FROM 
    table3 
    LEFT JOIN table1 on table3.id3 = table1.id1 
    LEFT JOIN table2 on table1.id1 = table2.id2 
+0

我雖然是正確的加入,但後來我認爲有超過2個表 – evilpenguin

0

使用union查詢

Declare @tbl1 as table 
(
id1 int 
) 
Declare @tbl2 as table 
(
id2 int 
) 

Declare @tbl3 as table 
(
id3 int 
) 

insert into @tbl1 values(1) 
insert into @tbl1 values(2) 
insert into @tbl1 values(3) 

insert into @tbl2 values(3) 
insert into @tbl2 values(4) 
insert into @tbl2 values(5) 

insert into @tbl3 values(5) 
insert into @tbl3 values(6) 
insert into @tbl3 values(7) 

SELECT 
* 
FROM 
(
    Select 
     T1.Id1, 
     T2.Id2, 
     T3.Id3 
    FROM @tbl3 T3 
    LEFT JOIN @tbl1 T1 ON T1.id1=T3.id3 
    LEFT JOIN @tbl2 T2 ON T3.id3=T2.id2 
    UNION 
    Select 
     T1.Id1, 
     T2.Id2, 
     T3.Id3 
    FROM @tbl1 T1 
    LEFT JOIN @tbl2 T2 ON T1.id1=T2.id2 
    LEFT JOIN @tbl3 T3 ON T1.id1=T3.id3 
    Union 
    Select 
     T1.Id1, 
     T2.Id2, 
     T3.Id3 
    FROM @tbl2 T2 
    LEFT JOIN @tbl1 T1 ON T1.id1=T2.id2 
    LEFT JOIN @tbl3 T3 ON T2.id2=T3.id3 
)X 
Order by ISNULL(X.id1,9) ,ISNULL(X.id2,9),X.id3 
1

該查詢爲您提供您所查找的輸出:

select t1.id1, t2.id2, t3.id3 
from table1 t1 
left join table2 t2 
on t1.id1 = t2.id2 
left join table3 t3 
on t2.id2 = t3.id3 
UNION 
select t1.id1, t2.id2, t3.id3 
from table2 t2 
left join table3 t3 
on t2.id2 = t3.id3 
left join table1 t1 
on t2.id2 = t1.id1 
UNION 
select t1.id1, t2.id2, t3.id3 
from table3 t3 
left join table2 t2 
on t3.id3 = t2.id2 
left join table1 t1 
on t3.id3 = t1.id1; 
+------+------+------+ 
| id1 | id2 | id3 | 
+------+------+------+ 
| 3 | 3 | NULL | 
| 1 | NULL | NULL | 
| 2 | NULL | NULL | 
| NULL | 5 | 5 | 
| NULL | 4 | NULL | 
| NULL | NULL | 6 | 
| NULL | NULL | 7 | 
------+------+------+ 
7 rows in set (0.00 sec)