希望这并不难解释。我需要使用第二个表中的地址更新第一个表
所以基本上,我的mytable1包含以下列:
id (pkey) | super_id | address | new_ref
101 | 1000 | 'wrong address' | empty
102 | 1000 | 'wrong address2' | empty
103 | 1000 | 'wrong address3' | empty
然后我的mytable2实际上具有正确的地址:
super_id | address | new_ref (pkey)
1000 | 'right address' | 1
1000 | 'right address2' | 2
1000 | 'right address3' | 3
我需要在mytable2中使用正确的地址填充mytable1,并且它们具有相同的super_id
但是,当我尝试这样做
update mytable1 a set address = (select address from mytable2 b where a.super_id = b.super_id)
它返回一个错误,因为显然是super_id被重复
是否可以将所有地址行更新到mytable1中?插入可能可以工作,但mytable1上已经有很多数据
答案 0 :(得分:2)
这很棘手。如果我理解正确,则需要枚举每个表以进行更新:
update mytable1 mt
set address = mt2.address
from (select mt.*, row_number() over (partition by super_id order by id) as seqnum
from mytable1 mt
) mt1 join
(select mt2.*, row_number() over (partition by super_id order by new_ref) as seqnum
from mytable2 mt2
) mt2
on mt2.super_id = mt1.super_id and mt2.seqnum = mt1.seqnum
where mt1.id = mt.id