oracle菜鸟学习之 复杂的更新语句使用
实例与答案
问题:表T1里有a,b,c...N个字段,表T2里有a,b,c三个字段,然后想在T1中"c"与表T2中"c"相同的情况下,从表T2中将a,b覆盖表T1中的a,b,怎么做?
实验表:
create table T1(a int,b int,c int,d int,e int);
create table T2(a int,b int,c int);
insert into T1 values(1,2,3,4,5);
insert into T1 values(10,20,3,4,5);
insert into T1 values(10,20,4,40,50);
insert into T2 values(-1,-1,3);
insert into T2 values(-2,-2,4);
查看表:
SQL> select * from T1;
A B C D E
---------- ---------- ---------- ---------- ----------
1 2 3 4 5
10 20 3 4 5
10 20 4 40 50
SQL> select * from T2;
A B C
---------- ---------- ----------
-1 -1 3
-2 -2 4
SQL>
思路:
更新数据的基本语句
update T1 set a=?,b=? where ?
怎么选出a呢?
SQL> select a.a from T2 a,T1 b where a.c=b.c;
A
----------
-1
-1
-2
SQL>
同样可以选出b
SQL> select a.b from T2 a,T1 b where a.c=b.c;
B
----------
-1
-1
-2
SQL>
where是什么?怎么从集合中取出唯一的值?
SQL> update T1 set a=(select a from T2 where T1.c=T2.c),b=(select b from T2 where T1.c=T2.c) where T1.c in (select c from T2);
3 rows updated.
SQL>
查看结果
SQL> select * from T1;
A B C D E
---------- ---------- ---------- ---------- ----------
-1 -1 3 4 5
-1 -1 3 4 5
-2 -2 4 40 50
SQL>