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

现在好了,执行很快。

猜你喜欢

转载自blog.csdn.net/samson_www/article/details/83893112