简体   繁体   中英

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? :

+------+------+------+------+
|  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:

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

Use a UNION subquery with all tables. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM