2013-07-30 88 views
2

我正在從一個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中選擇空值。

回答

2

如何:

SELECT t2.ID, t2.Description 
FROM table2 t2 
UNION ALL 
SELECT t1.ID, t1.Description 
FROM table1 t1 
WHERE NOT EXISTS (SELECT * 
        FROM table2 t2 
        WHERE t2.ID = t1.ID) 

上述查詢獲取所有記錄從表2(包括的情況下描述爲NULL但填充的ID),和只從表1,其中他們不記錄」噸表中存在2

1

這裏有一個選擇:

SELECT table2.* 
FROM table1 
    RIGHT JOIN table2 
     ON table1.id = table2.id 

UNION 

SELECT table1.* 
FROM table1 
    FULL OUTER join table2 
     ON table1.id = table2.id 
WHERE table1.id NOT IN (SELECT id FROM table2) 
--and table2.id not in (select id from table1) 

您可以在最後一行添加如果你不希望只在表2的ID。否則,我猜斯圖爾特安斯沃思的解決方案是更好的(即刪除所有連接)

http://sqlfiddle.com/#!3/03bab/12/0

+0

此解決方案的工作,但似乎比我的一些初步測試,原來的解決方案效率較低 – jeroenh

相關問題