很多場景我們需要依據兩個表的某個字段進行關聯更新。
select * from table1 t1;

select * from table2 t2;

現需求:參照table2表修改table1表,修改條件為兩表的fname列內容一致。
常見陷阱:update table1 t1 set t1.fmoney = (select t2.fmoney from table2 t2 where t2.fname = t1.fname)
執行后table1 結果如下:

有一行原有值,被更新成空值了。
正確寫法:
update table1 t1 set t1.fmoney = (select t2.fmoney from table2 t2 where t2.fname = t1.fname) where exists(select 1 from table2 t2 where t2.fname = t1.fname);

SQL模板:
update table1 t1 set t1.c= (select t2.c from table2 t2 where t1.a=t2.a) WHERE EXISTS(SELECT 1 FROM table2 t2 WHERE t2.a = t1.a);
當在t1.a=t2.a的條件下t2查詢出多條記錄時也會報錯,此時可以考慮將t2.c唯一化。常用的如下兩種方法
法一:取滿足條件的t2.c的最值
update table1 t1 set t1.c = (select max(t2.c) from table2 t2 where t1.a=t2.a) where exists(select 1 from table2 t2 where t2.a = t1.a);
法二:取滿足條件第一行的t2.c值
update table1 t1 set t1.c = (select t2.c from table2 t2 where t1.a=t2.a and rownum =1) where exists(select 1 from table2 t2 where t2.a = t1.a);
參考博文:ORACLE 兩表關聯更新三種方式
