我的问题是用 SQL Server 中的键替换。任何人都可以给我一个查询吗?
感谢您的回答!
表 1
:
ID | Code | Des | more columns
---+------+-----+-------------
1 | 100 | a | ...
2 | 200 | b | ...
3 | 300 |data3| ...
表 2
:
ID | Code | Des
---+------+------
1 | 100 | data1
2 | 200 | data2
结果一定是这样的:
ID | Code | Des | more columns
---+------+-----+-------------
1 | 100 |data1| ...
2 | 200 |data2| ...
3 | 300 |data3| ...
最佳答案
做一个LEFT JOIN
,如果没有table2.Des值,取table1.Des代替:
select t1.ID, t1.Code, coalesce(t2.Des, t1.Des), t1.more Column
from table1 t1
left join table2 t2 on t1.code = t2.code
或者,也许你想要这样:
select * from table2
union all
select * from table1 t1
where not exists (select 1 from table2 t2
where t2.code = t1.code)
即返回 table2 行,如果代码在 table1 但不在 table2 中,也返回该行。
关于sql - 在 SQL Server 中用 2 个表的键替换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36715245/