这是一个非常常用的关联更新方法,只要掌握了其中的小小的细节,一切都将是无比的自然与和谐。
实验目标:使用第二张表t_ref中的数据对第一张表t进行更新,如果t中存在t_ref中的数据,则进行相应的更新,如果不存在,则t中的数据保持不变。
1.创建测试表并初始化实验数据
sec@ora10g> create table t (x varchar2(10), y varchar2(10));
sec@ora10g> create table t_ref (x varchar2(10), y varchar2(10));
sec@ora10g> insert into t values ('A', 'Secooler');
sec@ora10g> insert into t values ('B', 'Secooler');
sec@ora10g> insert into t values ('C', 'Secooler');
sec@ora10g> insert into t values ('D', 'Secooler');
sec@ora10g> insert into t_ref values ('A', 'Andy');
sec@ora10g> insert into t_ref values ('B', 'Andy');
sec@ora10g> insert into t_ref values ('C', 'Andy');
sec@ora10g> commit;
2.查看实验表数据
sec@ora10g> select * from t;
X Y
---------- ----------
A Secooler
B Secooler
C Secooler
D Secooler
sec@ora10g> select * from t_ref;
X Y
---------- ----------
A Andy
B Andy
C Andy
3.我们完成使用t_ref的数据关联更新t表中的数据
1)错误的关联更新方法(“D”行数据应该保持不变,这种方法会将这一行更新为空)
sec@ora10g> UPDATE t
2 SET y =
3 (SELECT y
4 FROM t_ref
5 WHERE t.x = t_ref.x)
6 /
4 rows updated.
sec@ora10g> select * from t;
X Y
---------- ----------
A Andy
B Andy
C Andy
D
2)正确的关联更新方法
sec@ora10g> UPDATE t
2 SET y =
3 (SELECT y
4 FROM t_ref
5 WHERE t.x = t_ref.x)
6 WHERE t.x IN (SELECT t_ref.x FROM t_ref)
7 /
3 rows updated.
sec@ora10g> select * from t;
X Y
---------- ----------
A Andy
B Andy
C Andy
D Secooler
4.小结
发现其中的小小的技巧了吧,我们仅仅需要的是做一个where子句的限制即可。SQL是万物之源,万变不离其宗。
当然,如果t_ref中的数据是t的一个子集,也可以使用merge完成这个需求。
关于merge的用法,可以参考我另外一个小文儿《【实验】展示MERGE的强大魅力,精通者可飘过~~》http://space.itpub.net/519536/viewspace-615976。
Good luck.
-- The End --
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70034820/viewspace-2994170/
,如需转载,请注明出处,否则将追究法律责任。