我在表中有重复的行。
我有两个通过外键连接的表
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
如何将这个选择与订单表联系起来,删除重复的行并更新表?
最佳答案
要更新订单表,例如:
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
)
需要double子查询来避免MySQL错误
ERROR 1093 (HY000) at line 36: You can't specify target table 'regions' for update in FROM clause
。关于mysql - 如何删除重复的行并更新表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7234440/