4

Say we have the following tables t1 and t2:

t1:
id | column_1
-------------
 1 |   1
 2 |   2

t2:
id | column_2
-------------
 2 |   2
 3 |   3

and we want to find the following result:

id | column_1 | column_2
------------------------
 1 |  1       | 
 2 |  2       | 2
 3 |          | 3

This basically is the union of a right join with a left join. The following code works but feels clumsy:

(
    SELECT t1.id, t1.column_1, t2.column_2 
    FROM t1 
    LEFT JOIN t2 ON t1.id = t2.id
)
UNION
(
    SELECT t2.id, t1.column_1, t2.column_2 
    FROM t1 
    RIGHT JOIN t2 ON t1.id = t2.id
)

Is there a better way to achieve this?

1
  • here are the tables, if you want to try it: CREATE TABLE IF NOT EXISTS t1 ( id int(11) NOT NULL, column_1 int(11) NOT NULL ); INSERT INTO t1 (id, column_1) VALUES (1, 1), (2, 2); CREATE TABLE IF NOT EXISTS t2 ( id int(11) NOT NULL, column_2 int(11) NOT NULL ); INSERT INTO t2 (id, column_2) VALUES (2, 2), (3, 3); Commented Sep 17, 2009 at 19:25

3 Answers 3

10
select a.id, t1.column_1, t2.column_2
from (
    select id from t1
    union 
    select id from t2
) a
left outer join t1 on a.id = t1.id
left outer join t2 on a.id = t2.id
2
  • Thanks for this answer! I have a more complex example with two keys (test+question) but I was able to adapt your method. Here is my query. sqltest.net/#975330 Commented Jan 9, 2020 at 16:31
  • Great answer - and can be easily expanded to left joins on multiple CTEs (in addition to two as shown in example). Thank you.
    – veg2020
    Commented Sep 10, 2020 at 20:33
1

Try this one:

SELECT t1.id, t1.column_1, t2.column_2 
FROM t1 
FULL OUTER JOIN t2 ON (t1.id = t2.id)

Edit: Doesn't work, MySQL does not know FULL OUTER JOIN. Have a look here: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

0

Haven't tried this myself, but this might work:

SELECT t1.id, t1.column_1, t2.column_2, t2a.column_2
FROM t1     
LEFT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t2 AS t2a ON t1.id = t2a.id
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.