ORACLE中的多表关联更新

原文:http://www.cnblogs.com/rayman/archive/2005/03/27/126527.html

ORACLE中的多表关联更新 

假设我们有test1 ,test2 两表

create table test1(no number,name varchar2(10));
create table test2(no number,name varchar2(10));
insert into test1 values(1,'a');
insert into test1 values(2,'b');
insert into test1 values(3,'c');
insert into test2 values(1,'aa');
insert into test2 values(2,'bb');


至此:
test1
        NO NAME
---------- ----------
         1 a
         2 b
         3 c

test2
        NO NAME
---------- ----------
         1 aa
         2 bb

如果要将test1表与test2表NO字段相等的记录的name字段更新为与test2表中的name字
段的值.
即以下效果:
test1
        NO NAME
---------- ----------
         1 aa
         2 bb
         3 c

那么以下的语句
update test1 a set name=(select name from test2 b where a.no=b.no);
的效果为:
test1
        NO NAME
---------- ----------
         1 aa
         2 bb
         3

要出想要的效果,可以用下面的语句来实现.
update test1 a set name=(select name from test2 b where a.no=b.no) where
exists(select name from test2 b where a.no=b.no);

也可以用下面的语句来实现:
update (select a.name aname,b.name bname from test1 a,test2 b where
a.no
=b.no) set aname=bname;
不过有个前提,是给test2表的NO设为主键.
alter table test2 add primary key(no);

 
分类: oracle
 
0
0
 
(请您对文章做出评价)
 
« 博主前一篇:NHibernate加载程序集的问题
» 博主后一篇:HTTP状态码
posted @ 2005-03-27 09:10 Rayman 阅读(8712) 评论(0) 编辑 收藏

 
 
posted @ 2012-11-14 14:27  seasonzone  阅读(213)  评论(0)    收藏  举报