简体   繁体   中英

SQL join on second table all distinct rows showing a column from both tables

This might be a very simple sql however for the life of me, I can't seem to get the desired results.

For purposes of illustration, I have two tables, Table A and Table B with the following records in each table.

Thank you in advance and my apologies for the novice formatting on here.

表A

表B

Desired Results

结果表

You are looking for full join :

select id, a.col1, b.col2
from a full join
     b
     using (id);

If your database doesn't support full join , I would recommend:

select a.id, a.col1, b.col2
from a left join
     b
     on a.id = b.id
union all
select b.id, null, b.col2
from b
where not exists (select 1 from a where a.id = b.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