SQL> select * from t1;
ID USERNAME
---------- --------------------
1 tom1
2 tom2
3 tom3
SQL> select * from t2;
ID USERNAME
---------- --------------------
1 jack1
2 jack2
要求:把表t1中的username用表t2中相同ID的username替换
即:SQL> select * from t1;
ID USERNAME
---------- --------------------
1 jack1
2 jack2
3 tom3
方法一:
merget into t1 using t2 on (t1.id=t2.id)
when matched then
update set t1.username=t2.username;
方法二
update t1 set t1.username=(select t2.username from t2 where t2.id=t1.id) where exists(select 1 from t2 where t2.id=t1.id);
误区:
update t1 set t1.username=(select t2.username from t2 where t2.id=t1.id);
SQL> select * from t1;
ID USERNAME
---------- --------------------
1 jack1
2 jack2
3
可见这并不是想要的结果。主要是因为t1表中id=3的记录在t2中没找到,t2.username 是空值导致的。而方法二就很好的解决了空值问题:在表t2中存在,也就是找到id了,才i更新,不存在就不更新,id=3在表t2不存在,所以不会被更新为NULL值。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/27042095/viewspace-1118453/
,如需转载,请注明出处,否则将追究法律责任。