oracle两表关联更新方法

--创建两张测试表
create table table1(  
id varchar2(10) ,  
val varchar2(20)  
); 
create table table2(  
id 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');
commit; 

--查询一下两张表
select * from table1
select * from table2

--table1中ID=06 VAL有值,但是table2中ID无06,结果table1 id=06对应的VAL被清空
--这种写法,表2中id在表1中有的val就会被同步更新过去,表2没有的ID,表1对应VAL内容会被清空。
UPDATE table1 SET table1.val = (select table2.VAL from table2 where table2.ID = table1.ID);

--正确写法:对于 table1中存在,但是table2中没有的id字段记录,不做修改;
--这种写法,更新前先判断表1中对应的ID在表2中是否存在,不存在就跳过。存在就把表2的VAL更新过去
UPDATE table1 
SET table1.VAL = (select table2.VAL from table2 where table2.ID = table1.ID)
WHERE EXISTS(SELECT 1 FROM table2 WHERE table2.ID = table1.ID);

--跨表更新特定条件的一条记录到其它表
UPDATE table1 SET table1.VAL = (select table2.VAL from table2 where table2.ID = table1.ID) where table1.ID='03';

--删除测试表
DROP TABLE TABLE1;
DROP TABLE TABLE2;

 

posted @ 2022-10-04 00:15  IT情深  阅读(2833)  评论(0编辑  收藏  举报