Oracle多表关联更新

以前用过,记不清了。

今天要用,顺便记录一下。

更新为指定值的:

update aaa a set a.version = (select b.version from bbb b where a.col = b.colxx and ...)
where exists (select 1 from bbb b where a.col = b.colxx and ...)
;

更新为对应的查询结果的:

update aaa a set a.version = (select b.version from bbb b where a.col = b.colxx and ...)
where exists (select 1 from bbb b where a.col = b.colxx and ...)
;

这个还有一种写法:

也可以用下面的语句来实现:

update ( select a.name aname,b.name bname from test1 a,test2 b where
a.no
= b.no) set aname = bname;

不过有个前提,是给test2表的NO设为主键.

参考原址如下:

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值