Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
863 views
in Technique[技术] by (71.8m points)

sql - MySQL: Union of a Left Join with a Right Join

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...