简体   繁体   中英

Left join but maintain values where NULL may result in Microsoft SQL

I have two tables:

Table A:

id names
1   a
2   b
3   c

and Table B:

id names
1   x
2   y

I'd like to perform a left join of Table B on Table A that results in the following table:

id names
1   x
2   y
3   c

How can I do this in Microsoft SQL?

You could use COALESCE :

SELECT a.id, COALESCE(b.name, a.name) AS name
FROM tab1 a
LEFT JOIN tab2 b 
  ON a.id = b.id

I think you just want coalesce() :

select a.id, coalesce(b.name, a.name) as name
from a left join
     b
     on 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