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 ' );
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);
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;
a.no = b.no) set aname = bname;
alter table test2 add primary key(no);