2017-04-21 43 views
0

我可以更新,罰款,我可以刪除罰款,但我想同時做兩個。更新哪裏存在刪除行哪裏沒有

我有一個表弊這樣,列名

ref,fname,lname,add1,add2,add3,add4 

A1 a b c d h j 
S2 f d s e y t 
B3 j f s e o p 

其中第一列是唯一

那麼這樣

ref,fname,lname,add1,add2 

A1 b c d e 
B3 k g h t 

另一個表中的數據我想更新第一個表使用第二個並刪除任何不具有唯一性的行

所以最終結果需要如下表ORIG

A1 b c d e h j 
B3 k g h t o p 

我能夠一氣呵成嗎?

回答

2

我可能接近這個使用CTE:

with u as (
     update orig 
      set b = d.b, . . . 
      from data d 
      where d.a = orig.a 
     returning * 
    ) 
delete from orig 
    where not exists (select 1 from u where u.a = d.a); 

第一CTE更新行。第二個是刪除。

+0

做'沒有任何好處'(從u中選擇1,其中ua = da' vs'da不在(從u選擇ua)「? –

+0

給我一個語法錯誤ERROR:語法錯誤處於或接近」from「 LINE 8:刪除原始文件 ^ – Kilisi

+1

@Kilisi:這是一個錯誤的答案,你需要刪除CTE後的',' –

0

您可以使用相關子查詢此:

delete 
from orig o 
where not exists (
     select 1 
     from data d 
     where d.col1 = o.col1 
     ) 
+0

但是......當密鑰匹配時,操作需要更新。 –