2


我有两个名为t1(id,ref_id) and t2(ref_id,id)我需要使用来自 t2 ref_id 的数据更新 t1 的 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 ));

但没有结果。

4

1 回答 1

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);

这是一个 sqlfiddle 演示

由于我使用了窗口函数(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

这是另一个 sqlfiddle 演示

于 2013-02-17T10:00:33.260 回答