oracle菜鳥學習之 複雜的更新語句使用
阿新 • • 發佈:2018-11-20
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>