小编典典

MySQL:左联接与右联接的并集

sql

假设我们有下表t1和t2:

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

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

我们希望找到以下结果:

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

这基本上是右连接与左连接的并集。以下代码有效,但感觉很笨拙:

(
    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
)

有没有更好的方法来实现这一目标?


阅读 293

收藏
2021-03-10

共1个答案

小编典典

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
2021-03-10