我在表A中有重复的条目,如:
id | name
=========
1 blue
2 red
3 blue
4 blue
5 red
在表B中,表A中的id是外键,我想用表A中的最小id更新外键,然后从表A中删除重复项,因此表B当前看起来像这样
id | tableAId
=============
1 1
2 2
3 3
4 4
5 5
表B应该看起来像
id | tableAId
=============
1 1
2 2
3 1
4 1
5 2
表A应该看起来像:
id | name
=========
1 blue
2 red
UPDATE tableB
SET Id = (
SELECT MIN(Id) FROM tableB b
INNER JOIN tableA a on a.Id = b.Id
GROUP BY a.Name)
答案 0 :(得分:0)
使用cte查找最小值并使用它来更新tableb:
with cte as
(
select min(id) as id, name
from tablea
group by name
)
update b
set tableaid = c.id
from tableb b
inner join tablea a on a.id = b.tableaid
inner join cte c on c.name = a.name
然后从tablea中删除未使用的记录:
delete a
from tablea a
where not exists
(
select * from tableb b
where b.tableaid = a.id
)