1. 程式人生 > >Oracle的關聯表更新(二)

Oracle的關聯表更新(二)

oracle資料庫中有一個表formtable_main_159_dt1結構如下

mainid,id 161,100, 161,101, 161,102, 162,103 162,104 163,105 現在增加一個欄位序號,實現如下的效果 mainid,id,xuhao 161,100,1 161,101,2 161,102,3 162,103,4 162,104,5 163,105,6

先使用如下語句實現出效果。  select row_number() over(partition by mainid order by id ) as xh,id,mainid from formtable_main_159_dt1 然後用update語句去更新新增欄位中的值; 最先用:update t1 set t1.c1=(select c2 from t2 where t1.id=t2.id) where exists (select 1 from t2 where t2.id=t1.id)  update formtable_main_159_dt1 set xuhao=(select xuhao from (select  row_number() over(partition by mainid order by id ) as xuhao ,id from formtable_main_159_dt1) a1  where formtable_main_159_dt1.id=a1.id)  where  exists(select 1 from formtable_main_159_dt1,(select  row_number() over(partition by mainid order by id ) as xuhao ,id from formtable_main_159_dt1) a1  where formtable_main_159_dt1.id=a1.id)  執行時間很長,而且語句寫的感覺及其囉嗦。

於是換一種寫法:update (select t1.c1,t2.c2 from t1,t2 where t1.id=t2.id) t set c1=c2 update ( select a1.xuhao , a2.xh from formtable_main_159_dt1 a1,(select row_number() over(partition by mainid order by id ) as xh,id from formtable_main_159_dt1) a2 where a1.id=a2.id ) t set xuhao=xh

結果提示: ORA-01779: 無法修改與非鍵值儲存表對應的列

於是再換一種寫法:  update ( select xuhao, row_number() over(partition by mainid order by id ) as xh from formtable_main_159_dt1) t set xuhao=xh 結果又是提示錯誤: ORA-01732: 此檢視的資料操縱操作非法  原來這種update寫法需要主鍵的。

再換寫法:merge into t1 using (select t2.c2,t2.id from t2) t on (t.id=t1.id) when matched then update set t1.c1=t.c2   merge into  formtable_main_159_dt1 a1 using (select row_number() over(partition by mainid order by id ) as xh,id,mainid from formtable_main_159_dt1) a2 on (a1.id=a2.id)  when matched then update  set a1.xuhao=a2.xh

現在好了,執行很快。