我正在从一个sql查询应该'合并'记录从2表,即如果记录存在table2中,它应该采取那一个,否则它应该回落到table1中的值。从连接表中选择记录,如果它存在
在这个例子中,table1和table2只有2个字段(id是一个描述),但显然在现实中可能会有更多。
这里有一个小的测试案例:
create table table1 (id int, description nvarchar(50))
create table table2 (id int, description nvarchar(50))
insert into table1 values (1, 'record 1')
insert into table1 values (2, 'record 2')
insert into table1 values (3, 'record 3')
insert into table2 values (1, 'record 1 modified')
insert into table2 values (2, null)
查询的结果应该是这样的:
1, "record 1 modified"
2, null
3, "record 3"
这是我想出了。
select
case when table2.id is not null then
table2.id else table1.id
end as Id,
case when table2.id is not null then
table2.description
else
table1.description
end as Description
-- etc for other fields
from table1
left join table2 on table1.id = table2.id
有没有更好的方法来实现我想要的?我不认为我可以使用3210,因为如果table1中的对应值不为null,那么它将不会从table2中选择空值。
此解决方案的工作,但似乎比我的一些初步测试,原来的解决方案效率较低 – jeroenh