2017-09-09 28 views
1

更新專欄中,我有兩個表:甲骨文:根據列從另一個表

enter image description here

列A是上,我們將採取加盟的列。我需要更新,如:

B = if(D not null) then D 
    else C 

我嘗試這樣做:

update Tab1 x 
set B = case when 
     (select D from Tab2 t2 
     inner join Tab1 t1 
     on t1.A = t2.A 
     where t1.A = x.A) is not null 
then (select D from Tab2 t2 
     inner join Tab1 t1 
     on t1.A = t2.A 
     where t1.A = x.A) 
else x.D END 
where x.A > (user_input) and x.A <= (user_input) 

這給了我輸出:0行更新。

另外,作爲一個說明,我需要在一個更新語句本身做到這一點。表Tab1中還有其他非依賴列可在此更新中更新。

我知道這看起來很亂,而且兩次執行相同的select子查詢並不是最優化的,但我並不真正瞭解如何實現這一點。

任何幫助或指針表示讚賞!

回答

1

我覺得MERGE是做多表更新的最佳方法:

merge into tab1 t1 
using tab2 t2 
on (
    t1.a = t2.a 
    and t1.a between 1 and 10 -- change this as needed 
) 
when matched then 
    update set t1.b = coalesce(t2.d, t1.c); 
1

應該是這樣

update Tab1 t1 
set t1.B = nvl((select t2.d from Tab2 t2 where t2.a = t1.a), t1.c) 
where t1.a = :user_input 

順便說一句,在0 rows updated與在那裏的條件做你的更新。看起來它不匹配您表中的任何記錄Tab1 - 因爲您的對帳單where x.A > (user_input) and x.A <= (user_input)將始終評估爲false

0
merge into tab1 t1 
using tab2 t2 
on ( t1.a = t2.a) 
when matched then 
    update set t1.b = case when t2.d is not null then t2.d else t1.c end 
;