如何删除重复的行并更新表

时间:2011-08-29 18:46:55

标签: mysql

我在表格中有重复的行。

我有两个用外键连接的表

regions (id)
orders (region_id)

这些地区有重复的名称。我想删除这些重复的行和更新订单表,复制的外键现在将被设置为仅保留区域表中的现有名称。

示例:

regions table:

id  name
1 | test
2 | test
3 | foo

orders table:

id region_id
6 | 1
7 | 2
9 | 3

我想要

orders table:

id region_id
6 | 1
7 | 1
9 | 3

regions table:

id  name
1 | test
3 | foo

我可以使用此SQL获取重复的行:

SELECT name, count(id) as cnt FROM regions 
GROUP BY name HAVING cnt > 1

如何将此选择与订单表连接并删除重复的行并更新表?

1 个答案:

答案 0 :(得分:5)

更新订单表,例如:

update  orders
join    regions r1
on      r1.id = orders.region_id
set     orders.region_id = 
        (
        select  min(r2.id)
        from    regions r2
        where   r2.name = r1.name
        )

之后,您可以删除重复的行:

delete  regions
from    regions
where   id not in
        (
        select  id
        from    (
                select  min(id) as id
                from    regions
                group by
                    name
                ) as SubqueryAlias
        )

需要双子查询来避免MySQL错误ERROR 1093 (HY000) at line 36: You can't specify target table 'regions' for update in FROM clause