2011-08-29 52 views
5

我在表中有重复的行。如何删除重复的行并更新表

我有一个由外键

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 

我如何连接这个选择与顺序表和删除重复行和更新表?

+0

重复保存记录的逻辑是什么?我假设第一个(即最低的主键)。你有机会获得另一项技术吗?直接使用MySQL可能很难做到这一点。 –

+1

Lukas它不只是删除行。我需要更新外键! – senzacionale

+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

+0

@senzacionale:奇怪的是,它可以在我的MySQL安装 – Andomar

+0

thx上寻求帮助。我不知道你需要这样的子查询。 – senzacionale