方法一:
sql> update wwm2
2 set town=(select town from wwm5 where wwm5.id=wwm2.id)
3 where id=(select wwm5.id from wwm5 where wwm5.id=wwm2.id)
4 /8 rows updated.
方法二: 與方法一道理相同,這裡需要掌握exist的相關用法.
sql> update wwm2
set town=(select town from wwm5 where wwm5.id=wwm2.id)
where exists (select 1 from wwm5 where wwm5.id=wwm2.id)
8 rows updated.
方法三:
sql> update (select a.town atown,a.id aid,b.town btown,b.id bid from wwm2 a,wwm5 b where a.id=b.id)
2 set atown=btown
3 /set atown=btown
*error at line 2:
ora-01779: cannot modify a column which maps to a non key-preserved table
1* alter table wwm5 add primary key (id)
sql> /
table altered.
1 update (select a.town atown,a.id aid,b.town btown,b.id bid from wwm2 a,wwm5 b where a.id=b.id)
2* set atown=btown
sql> /
8 rows updated.
這種方法的侷限性就是需要primary 的支援.
方法四:
1 declare
2 cursor cur_wwm is select town,id from wwm5;
3 begin
4 for my_wwm in cur_wwm loop
5 update wwm2 set town=my_wwm.town
6 where id=my_wwm.id;
7 end loop;
8* end;
sql> /
pl/sql procedure successfully completed.
sql> select * from wwm2;
town id
-------------------- ----------
222 222
lllldf 111
lllldf 111
llll 1111
dddd 2222
lllldf 111
lllldf 111
lllldf 111
lllldf 111
ljjjjj 222
lllldf 111
town id
-------------------- ----------
lllldf 111
ljjjjj 222
這個方法是最靈活的了.
方法五:
注意,方法五只能適用於wwm5是wwm2的子集的時候.
1 merge into wwm2
2 using (select town,id from wwm5) b
3 on (wwm2.id=b.id)
4 when matched then update set town=b.town
5* when not matched then insert (town,id) values (null,null)
sql> /
9 rows merged.
sql> select * from wwm2;
town id
-------------------- ----------
---注意這個地方,被插入了乙個空值.因為wwm5的id=9984在wwm2中不能匹配,根本原因是oracle9必須有when not matched子句,但是oracle10可以不許要,也就是oracle10可以不寫when not matched ,就不必插入null值了,為解決這個問題,下一步會delete wwm5的id=9984,這樣一來就不會執行when not matched
222 222
lllldf 111
lllldf 111
llll 1111
dddd 2222
lllldf 111
lllldf 111
lllldf 111
lllldf 111
ljjjjj 222
town id
-------------------- ----------
lllldf 111
lllldf 111
ljjjjj 222
14 rows selected.
sql> delete from wwm5 where id=9984;
1 row deleted.
sql> 1 merge into wwm2
sql> 2 using (select town,id from wwm5) b
sql> 3 on (wwm2.id=b.id)
sql> 4 when matched then update set town=b.town
sql> 5* when not matched then insert (town,id) values (null,null)
sql> /
8 rows merged.
以上就是5種關連更新的例子了,希望能給開發人員解惑.
說明:如果select 子句可以返回多行記錄,但返回適合where條件的記錄只能是唯一的,否則將會報返回單行的select子句返回多行的錯誤,因為update只能跟據此處的where子句(內層where)進行相應記錄的匹配更新,一次只能是一條。
在Oracle 裡面建立job
1 建立測試表 create table a a date 2 建立儲存過程 create or replace procedure b as begin insert into a values sysdate end 3 提交建立job variable aaa number begin dbm...
在oracle裡面寫case語句
例子 在乙個表 tablename 中由於乙個字段 flag 的取值不同,對另乙個字段 value 分別作多次sum.selectid,nvl sum case whenflagis null thenvalue end 0 value a,nvl sum case whenflagisnot nu...
ORACLE裡面的外連線和
oracle裡面的外連線可以簡寫成 右連線的簡寫 也就是 保留右表存在,左表不存在的行 左連線 也就是 保留左表存在,右表不存在的行 對於這種簡寫的侷限性是顯而易見的 可讀性就很差,需要花時間去理解.因為我們的思維方式是 首先是怎麼去連線,然後用什麼條件過濾 分成兩步走,便使得sql清晰易懂.記得在...