连接3个表,包括空值

时间:2016-07-29 06:47:50

标签: mysql sql

我有3个表table1有列id1,其中包含三个值' 1',' 2',' 3'和table2的列id2有三个值' 3',' 4'' 5'和table3的列id3有三个值' 5'' 6'' 7'我如何加入所有三个表,并且我还希望显示空值。请参阅下面的示例。

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
有些人确实帮我搞糊涂了

3 个答案:

答案 0 :(得分:1)

你需要一个完整的外连接,遗憾的是,MySQL没有完整的外连接。有SoundPlayer.Play,但它仍然开放。

你必须通过循环地在几个左连接之间进行联合来模拟它们:

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

答案 1 :(得分:1)

此查询为您提供所需的输出:

margin: 107.402pt 56.693pt 99.213pt 53.858pt;

答案 2 :(得分:0)

使用联合查询

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