Oracle中 如何用一個表的數(shù)據(jù)更新另一個表中的數(shù)據(jù)

建表語句:

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表如下:
image.png
image.png
要將 table2中idd - val 的值,賦值給table1對應(yīng)的 idd - val;

注意:

  • table1中 有 2個 idd 為 02,val 不同;
  • table2中 有 05,table1中沒有;
  • table1中 有 06,table2中沒有。

sql語句:

  1. 通過子查詢 ,直接 update 更新,如下:
    update table1 set table1.val = (select val from table2 where table1.idd = table2.idd);


    image.png
  • 問題:對于 table1中idd存在,table2中不存在,val變成了null;
  1. 改進,加入限制條件,對于 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
  1. 使用merge,如下:
    merge into table1
    using table2
    on (table1.idd = table2.idd)
    when matched then
    update set table1.val = table2.val
  1. 在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。

參考:Oracle中用一個表的數(shù)據(jù)更新另一個表的數(shù)據(jù)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容