Suppose we have the need for a query performing two FULL JOIN
s (in PostgreSQL terminology) over table1-3, where table2 and table3 both have foreign keys pointing into table1. This shall work in MySQL, where FULL JOIN
is not available. Thus a workaround has to be found.
Starting with LEFT JOIN
s, the following code works as described in (1):
SELECT table1.ID, table1.x, table2.y, table3.z
FROM (table1
LEFT JOIN table2
ON table1.ID = table2.FOREIGN_ID)
LEFT JOIN table3
ON table1.ID = table3.FOREIGN_ID
Following (2), I'm able to emulate a full outer join using the UNION
statement for a single join:
SELECT table1.ID, table1.x, table2.y
FROM table1
LEFT JOIN table2
ON table1.ID = table2.FOREIGN_ID
UNION
SELECT table1.ID, table1.x, table2.y
FROM table1
RIGHT JOIN table2
ON table1.ID = table2.FOREIGN_ID
yielding
and
SELECT table1.ID, table1.x, table3.z
FROM table1
LEFT JOIN table3
ON table1.ID = table3.FOREIGN_ID
UNION
SELECT table1.ID, table1.x, table3.z
FROM table1
RIGHT JOIN table3
ON table1.ID = table3.FOREIGN_ID
ORDER BY ID
yielding
I need advice about how to get to this output from here:
That is, the result rows, which reference an entry from table1 via foreign key should be joined soundly, while the stray entries from table2 and table3 (those with foreign key NULL) should be listed in extra rows (y2 and z4 in the example).