很抱歉,如果描述不正确,我不是SQL专家......
我有以下查询 -
SELECT t1.ids, t1.name, t2.ids t3.ids FROM tab1 t1
LEFT JOIN tab2 t2 on t2.ids = t1.ids
LEFT JOIN tab3 t3 on t3.ids = t1.ids
此查询的结果是返回tab1
的所有内容,如果tab2
或tab3
中没有匹配,则会将字段显示为空...
| t1.ids | t1.name | t2.ids | t3.ids |
| 1 | n1 | null | 1 |
| 2 | n2 | 2 | null |
我需要的是,如果tab1
与tab2
或tab3
中的某些内容不匹配,仍会返回tab2
和tab3
行,但{ {1}}字段为null,如下所示:
tab1
知道最有效的方法是什么?
答案 0 :(得分:1)
你想要的是一个FULL OUTER JOIN
,遗憾的是在MySQL中没有。在这种情况下,您可以使用UNION ALL
:
SELECT t1.ids, t1.name, t2.ids t3.ids
FROM tab1 t1
LEFT JOIN tab2 t2 on t2.ids = t1.ids
LEFT JOIN tab3 t3 on t3.ids = t1.ids
UNION ALL
-- Get all t2 rows having no match in t1
SELECT t1.ids, t1.name, t2.ids t3.ids
FROM tab2 t2
LEFT JOIN tab1 t1 on t2.ids = t1.ids
LEFT JOIN tab3 t3 on t3.ids = t2.ids
WHERE t1.id IS NULL
UNION ALL
-- Get all rows in t3 having no match in t1 AND no match
-- in t2. Rows of t3 having no match in t1 and a match in t2
-- are returned by th previous query.
SELECT t1.ids, t1.name, t2.ids t3.ids
FROM tab3 t3
LEFT JOIN tab1 t1 on t3.ids = t1.ids
LEFT JOIN tab2 t2 on t2.ids = t3.ids
WHERE t1.id IS NULL AND t2.id IS NULL
答案 1 :(得分:0)
您正在寻找MySQL不支持的完整外连接。最简单的方法是首先选择所有ID,然后选择外连接所有表:
SELECT t1.ids, t1.name, t2.ids t3.ids
FROM (SELECT ids FROM tab1 UNION SELECT ids FROM tab2 UNION SELECT ids FROM tab3) x
LEFT JOIN tab1 t1 on t1.ids = x.ids
LEFT JOIN tab2 t2 on t2.ids = x.ids
LEFT JOIN tab3 t3 on t3.ids = x.ids;