建表語句:
create table table1(
idd varchar2(10) ,
val varchar2(20)
);
create table table2(
idd varchar2(10),
val varchar2(20)
);
插入資料:
insert into table1 values ('01','1111');
insert into table1 values ('02','222');
insert into table1 values ('02','2222');
insert into table1 values ('03','3333');
insert into table1 values ('04','4444');
insert into table1 values ('06','6666');
commit;
insert into table2 values ('01','aaaa');
insert into table2 values ('02','bbbb');
insert into table2 values ('03','cccc');
insert into table2 values ('04','dddd');
insert into table2 values ('05','eee');
insert into table2 values ('05','eeee');
commit;
2表如下:

image.png

image.png
要将 table2中idd - val 的值,指派給table1對應的 idd - val;
注意:
table1中 有 2個 idd 為 02,val 不同;
table2中 有 05,table1中沒有;
table1中 有 06,table2中沒有。
sql語句:
通過子查詢 ,直接 update 更新,如下:
update table1 set table1.val = (select val from table2 where table1.idd = table2.idd);

image.png
問題:對于 table1中idd存在,table2中不存在,val變成了null;
改進,加入限制條件,對于 table1 中有,但是table2中不存在的idd,不做修改;
update table1 set val = (select val from table2 where table1.idd = table2.idd)
where exists (select 1 from table2 where table1.idd = table2.idd)

image.png
但上述2種寫法,遇到table2中繼續插入資料,
insert into table2 values ('03','ccc');
即table2 中有一個idd對應多個val,并且在table1中有對應idd時。
使用merge,如下:
merge into table1
using table2
on (table1.idd = table2.idd)
when matched then
update set table1.val = table2.val
遇到 table2 中有一個idd對應多個val,并且在table1中有對應idd時,報錯如下:

image.png
ORA-30926: 無法在源表中獲得一組穩定的行
在3的基礎上,加入限制條件;
merge into table1
using (select t.idd ,max(t.val) m from table2 t group by t.idd)table2
on (table1.idd = table2.idd)
when matched then
update set table1.val = table2.m
上述寫法在 using後面構造了一個新的table2,group by idd,但一定要對val做出處理,如果是varchar類型,可以選擇 max,min等函數,如果number類型,可以使用sum,avg等函數,總之,要對val做出篩選,新的table2是一個idd對應一個val。