我有两个名为t1(id,ref_id) and t2(ref_id,id)
的表我需要更新t1的ref_id列,该列使用来自t2 ref_id的数据为空。其中id t1.id和t2.id具有相同的值。
t1已经
ID REF_ID
123
123
124
124
124
125
t2有
REF_ID ID
2010 123
2011 123
2012 124
2013 125
2014 124
2015 124
我的输出是
123 2010
123 2011
124 2012
125 2013
124 2014
124 2015
可以通过单个更新语句完成吗? 我试过这个
update test_01 t1 set t1.ref_id=(select * from(select t2.ref_id from test_02 t2 order by t2.id ));
但没有结果。
答案 0 :(得分:2)
试试这个:
update t1
set ref_id = (select t22.ref_id
from (select rowid ri, id, ref_id, row_number() over (partition by id order by 1) rn
from t1 ) t11 join
(select id, ref_id, row_number() over (partition by id order by 1) rn
from t2) t22 on t11.id = t22.id and t11.rn = t22.rn
where t11.ri = t1.rowid);
由于我使用了窗口函数(row_number),您可能会考虑使用合并:
merge into t1 d
using (
select t22.ref_id, t11.ri
from (select rowid ri, id, ref_id, row_number() over (partition by id order by 1) rn
from t1 ) t11 join
(select id, ref_id, row_number() over (partition by id order by 1) rn
from t2) t22 on t11.id = t22.id and t11.rn = t22.rn
) s
on (d.rowid = s.ri)
when matched then update set d.ref_id = s.ref_id