2015年5月27日

[ORACLE] UPDATE時 撘配EXISTS關鍵字

有時UPDATE時 會用到子查詢


update member
set  unit =(select unit from member_sync
where member.oid = member_sync.oid
and member.unit <>member_sync.unit)


腦中覺得  這樣下 就是update member裡的unit 和member_sync 有同樣oid 但unit不同的資料們

but~~~~

這樣下完  會整張member的unit都被update了 而且欄位還都變成null..........



google後 看到 http://www.techonthenet.com/oracle/update.php
寫說要加上"EXISTS"

You may wish to update records in one table based on values in another table. Since you can't list more than one table in the Oracle UPDATE statement, you can use the Oracle EXISTS clause.


所以寫法就變成
update member
set  unit =(select unit from member_sync
where member.oid = member_sync.oid
and member.unit <>member_sync.unit)

WHERE EXISTS (select unit from member_sync
where member.oid = member_sync.oid
and member.unit <>member_sync.unit)


原因在http://blog.xuite.net/twoli1102/work/65466674-Update%E8%AA%9E%E5%8F%A5%E5%84%AA%E5%8C%96
裡提到
Update語句的原理是先根據where條件查到資料後,如果set中有子查詢,則執行子查詢把值查出來賦給更新的欄位,執行更新。

 如:
update 表a set a.欄位1 = (select b.欄位1 from 表b where a.欄位2=b.欄位2) where exists(select 1 from 表b where a.欄位2=b.欄位2)。

查表a的所有資料,迴圈每條資料,驗證該條資料是否符合exists(select 1 from 表b where a.欄位2=b.欄位2)條件,如果是則執行(select b.欄位1 from 表b where a.欄位2=b.欄位2)查詢,查到對應的值更新a.欄位1中。
關聯表更新時一定要有exists(select 1 from 表b where a.欄位2=b.欄位2)這樣的條件,否則將表a的其他資料的欄位1更新為null值。




沒有留言:

張貼留言