2014-04-07 40 views
0

我在表格中的重复的条目,如:使用另一个表更新表中的外键?

id | name 
========= 
1 blue 
2 red 
3 blue 
4 blue 
5 red 

表B,从表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

我曾尝试基于tableB的更新在分组的名称和带回min(id),但这会抛出一个错误,因为我试图将一个字段设置为多个值 – xaisoft

+0

向我们展示您尝试的内容,以便我们可以从中取出它。 – Crono

+0

@Crono - 更新后,但不起作用。我基本上想在实际删除表A中的行之前用min(id)更新已删除的id。 – xaisoft

回答

0

查找最小值的CTE,并用它来更新表B:

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 
) 
相关问题