建表語句:
create table table1(
idd varchar2(10) ,
val varchar2(20)
);
create table table2(
idd varchar2(10),
val varchar2(20)
);
插入數(shù)據(jù):
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表如下:


要將 table2中idd - val 的值,賦值給table1對應(yīng)的 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中繼續(xù)插入數(shù)據(jù),
insert into table2 values ('03','ccc');
即table2 中有一個idd對應(yīng)多個val,并且在table1中有對應(yīng)idd時。 - 執(zhí)行后會報錯:
ORA-01427:單行子查詢返回多個行
image.png
- 使用merge,如下:
merge into table1
using table2
on (table1.idd = table2.idd)
when matched then
update set table1.val = table2.val
- 遇到 table2 中有一個idd對應(yīng)多個val,并且在table1中有對應(yīng)idd時,報錯如下:
image.png
ORA-30926: 無法在源表中獲得一組穩(wěn)定的行
- 在3的基礎(chǔ)上,加入限制條件;
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后面構(gòu)造了一個新的table2,group by idd,但一定要對val做出處理,如果是varchar類型,可以選擇 max,min等函數(shù),如果number類型,可以使用sum,avg等函數(shù),總之,要對val做出篩選,新的table2是一個idd對應(yīng)一個val。



