[英]How to format a FULL OUTER JOIN for more than two tables in mySQL?
I have four tables. 我有四个桌子。
Table A Table B Table C Table D
+----+ +------+ +------+ +------+
| id | | id | | id | | id |
+----+ +------+ +------+ +------+
| 1 | | 2 | | 3 | | 4 |
+----+ | 4 | +------+ +------+
+------+
Is there a query that does to do a FULL OUTER JOIN such that the output is this? 是否存在执行FULL OUTER JOIN这样的输出的查询? :
:
+------+------+------+------+
| id | id | id | id |
+------+------+------+------+
| 1 | NULL | NULL | NULL |
| NULL | 2 | NULL | NULL |
| NULL | NULL | 3 | NULL |
| NULL | 4 | NULL | 4 |
+------+------+------+------+
I know how to do this for 2 tables: 我知道如何为2个表执行此操作:
SELECT * FROM table_a
LEFT JOIN table_b ON table_a.res_id = table_b.res_id
UNION
SELECT * FROM table_a
RIGHT JOIN table_b ON table_a.res_id = table_b.res_id;
But I don't know how to do this for more than 2 tables. 但是我不知道如何对两个以上的表执行此操作。
Any help appreciated. 任何帮助表示赞赏。
SQL Fiddle: http://sqlfiddle.com/#!9/58f416/1 SQL小提琴: http ://sqlfiddle.com/#!9/58f416/1
Use a UNION subquery with all tables. 对所有表使用UNION子查询。 Then LEFT JOIN the four tables with it:
然后,用它左联接四个表:
SELECT
a.res_id as a_id,
b.res_id as b_id,
c.res_id as c_id,
d.res_id as d_id
FROM (
SELECT res_id FROM table_a
UNION
SELECT res_id FROM table_b
UNION
SELECT res_id FROM table_c
UNION
SELECT res_id FROM table_d
) u
LEFT JOIN table_a a ON a.res_id = u.res_id
LEFT JOIN table_b b ON b.res_id = u.res_id
LEFT JOIN table_c c ON c.res_id = u.res_id
LEFT JOIN table_d d ON d.res_id = u.res_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.