Oracle中 如何用一个表的数据更新另一个表中的数据

2017-12-13  本文已影响43人  kangkaii
建表语句:

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;

注意:

sql语句:

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


    image.png
  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
  1. 使用merge,如下:
    merge into table1
    using table2
    on (table1.idd = table2.idd)
    when matched then
    update set table1.val = table2.val
  1. 在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

参考:Oracle中用一个表的数据更新另一个表的数据

上一篇 下一篇

猜你喜欢

热点阅读