完全加入3个表

时间:2012-10-25 04:36:39

标签: mysql join

我有这个查询来模拟mysql中的三个表的full join

SELECT a. * , b. * , c. *
FROM tbl_1 a
LEFT OUTER JOIN tbl_2 b ON a.num = b.num
LEFT OUTER JOIN tbl_3 c ON a.num = c.num
UNION
SELECT a. * , b. * , c. *
FROM tbl_1 a
RIGHT OUTER JOIN tbl_2 b ON a.num = b.num
RIGHT OUTER JOIN tbl_3 c ON a.num = c.num

但它产生的结果并不是我所期望的,我要加入的表格如下,

Table1-
num |info
----------
1   |aaaaa  
2   |bbbb
3   |ccc
3   |ccc
4   |dddd

Table2-
num |info
----------
1   |aaaaa
3   |ccc
4   |dddd
5   |eeee
6   |ffff

Table3-
num |info
----------
1   |aaaaa
6   |ffff
2   |bbbb

我期待的结果是,

Required result 1-
num |info   num |info   num |info
----------- ----------- ----------
1   |aaaaa  1   |aaaaa  1   |aaaaa
2   |bbbb   NULL|NULL   2   |bbbb
3   |ccc    3   |ccc    NULL|NULL
3   |ccc    3   |ccc    NULL|NULL
4   |dddd   4   |dddd   NULL|NULL
NULL|NULL   5   |eeee   NULL|NULL
NULL|NULL   6   |ffff   6   |ffff

Required result 2-
num |info   num |info   num |info
----------- ----------- ----------
1   |aaaaa  1   |aaaaa  1   |aaaaa
2   |bbbb   NULL|NULL   2   |bbbb
3   |ccc    3   |ccc    NULL|NULL
3   |ccc    3   |ccc    NULL|NULL
4   |dddd   4   |dddd   NULL|NULL
NULL|NULL   6   |ffff   6   |ffff

但我得到的是

Result i get-
num |info   num |info   num |info
----------- ----------- ----------
1   |aaaaa  1   |aaaaa  1   |aaaaa
2   |bbbb   NULL|NULL   2   |bbbb
3   |ccc    3   |ccc    NULL|NULL
3   |ccc    3   |ccc    NULL|NULL
4   |dddd   4   |dddd   NULL|NULL
NULL|NULL   NULL|NULL   6   |ffff
NULL|NULL   NULL|NULL   2   |bbbb

我可能知道这里有什么问题,我已经坚持了2天并且无法解决..我知道查询以获得我想要的结果吗?

非常感谢:)

1 个答案:

答案 0 :(得分:1)

这就像John Woo对sql小提琴的评论所示。 (原始答案包含错误但现在应该有效)

SELECT a. * , b. * , c. *
FROM tbl_1 a
LEFT OUTER JOIN tbl_2 b USING (num)
LEFT OUTER JOIN tbl_3 c USING (num)
UNION
SELECT a. * , b. * , c. *
FROM tbl_2 b
LEFT OUTER JOIN tbl_1 a USING (num)
LEFT OUTER JOIN tbl_3 c USING (num)
UNION
SELECT a. * , b. * , c. *
FROM tbl_3 c
LEFT OUTER JOIN tbl_1 a USING (num)
LEFT OUTER JOIN tbl_2 b USING (num)