我正在從一個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