2017-10-04 35 views
4

我不是很擅長SQL,我已經嘗試了一些東西。考慮到性能的代碼,將這5條更新語句合併爲一條語句的最佳方法是什麼?會是一個很大的幫助。非常感謝!合併多個SQL更新語句(甲骨文)

代碼:

----------------1 

Update main_table 
set a = (case 
..some code.. end) 
where condition_2; 

----------------2 

Update main_table 
set b = (case 
..some code.. end) 
where condition_2 

----------------3 

Update main_table 
set c = (select x from sec_table where conditon_1) 
where condition_2 

----------------4 

Update main_table 
set d = (select y from sec_table where conditon_1) 
where condition_2 

----------------5 

Update main_table 
set e = (select z from sec_table where conditon_1) 
where condition_2 
+0

我已經嘗試過這一點,但我m尋找更好的表現: UPDATE main_table SET \t a =(CASE 部分代碼 END), \t B =(CASE 一些代碼 END), C = (選擇x FROM sec_table WHERE condition_2) d = (選擇Y FROM sec_table WHERE condition_2) e = (SELECT z FROM sec_table where condition_2) WHERE condition_1; – Vidit

回答

3

我認爲你可以爲這樣寫:

update main_table 
    set a = (case ..some code.. end), 
     b = (case ..some code.. end), 
     (c, d, e) = (select x, y, z from sec_table where conditon_1) 
where condition_2 
+0

我試過這個,但是----(c,d,e)=(從sec_table中選擇x,y,z,其中conditon_1)----這部分代碼給了我一些意想不到的結果。 – Vidit

+0

我相信我在where子句中的條件做錯了什麼 – Vidit

0

,你只能在一個update語句執行。根據你在sec_table上創建的子查詢,你甚至可以調整更多。

update main_table set a= (case ..some code.. end), 
         b= (case ..some code.. end), 
         c= (select x from sec_table where conditon_1),  
         d= (select y from sec_table where conditon_1), 
         e= (select z from sec_table where conditon_1) 
where condition_2 
2

你可以結合你的更新查詢,並且只使用一個像這樣的查詢:

UPDATE main_table 
    SET a = (case ..some code.. end) , 
     b = (case ..some code.. end) ... /*the rest of your sets*/ 
    where /*add your conditions*/