简体   繁体   中英

"merge" two tables in SQL

I have two tables - tbl1,tbl2.

tbl1

(id int, name string):

(1, dan),
(2, shon),
(3, mimi),
(4, mali).

tbl2

(int id, second_name string):

(1, shiri),
(3, mili).

I want to do a "join" using the id but I don't want the ids that are in tbl1 and no in tbl 2 to disappear.

If I will do join the output will be:

(1, dan, shiri),
(3, mimi, mili).

but the output that I need is:

(1, dan, shiri),
(2, shon, *blank/null*),
(3, mimi, mili),
(4, mali, *blank/null*).

Please help me!

It sounds like you want a LEFT OUTER JOIN . Assuming you are using SQL Server, it would be like this:

SELECT tbl1.id, tbl1.name, tbl2.second_name 
    FROM tbl1 
    LEFT OUTER JOIN tbl2 ON tbl1.id = tbl2.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