我有一个包含 8 列的表格,但随着时间的推移,我发现了很多重复项。我已经查看了具有类似主题的其他问题,但它并没有解决我目前遇到的问题。
+---------------------------------------------------------------------------------------+
| id | market | agent | report_name | producer_code | report_date | entered_date | sync |
+---------------------------------------------------------------------------------------+
定义唯一条目的是基于市场、代理、report_name、producer_code 和 report_date 字段。我正在寻找的是一种列出所有重复条目并将其删除的方法。或者只是删除重复的条目。
我考虑过用脚本来做,但该表包含 250 万个条目,而且所花费的时间是不可行的。
有人可以提出任何替代方案吗?我看到人们使用以下查询获得重复项列表,但不确定如何根据我的情况调整它:
SELECT id, count(*) AS n
FROM table_name
GROUP BY id
HAVING n > 1
最佳答案
以下是您可能会考虑的两种策略。您必须根据您实际认为的重复项来调整用于选择重复项的列。除了 id 列之外,我只包含了您列出的所有列。
第一个简单地创建一个没有重复的新表。有时这实际上比尝试删除所有有问题的行更快更容易。只需创建一个新表,插入唯一行(我使用 min(id) 作为结果行的 ID),重命名这两个表,然后(一旦您对一切正常工作感到满意)删除原始表。当然,如果您有任何外键约束,您也必须处理这些约束。
create table table_copy like table_name;
insert into table_copy
(id, market, agent, report_name, producer_code, report_date, entered_date, sync)
select min(id), market, agent, report_name, producer_code, report_date,
entered_date, sync
from table_name
group by market, agent, report_name, producer_code, report_date,
entered_date, sync;
RENAME TABLE table_name TO table_old, table_copy TO table_name;
drop table table_old;
第二种策略只删除重复项,它使用一个临时表来保存有关哪些行具有重复项的信息,因为 MySQL 不允许您从要在子查询中删除的同一个表中进行选择。只需创建一个临时表,其中包含标识重复项的列以及一个实际保存要保留的 ID 的 id 列,然后您可以执行多表删除,在其中连接两个表以仅选择重复项。
create temporary table dups
select min(id), market, agent, report_name, producer_code, report_date,
entered_date, sync
from table_name
group by market, agent, report_name, producer_code, report_date,
entered_date, sync
having count(*) > 1;
delete t
from table_name t, dups d
where t.id != d.id
and t.market = d.market
and t.agent = d.agent
and t.report_name = d.report_name
and t.producer_code = d.producer_code
and t.report_date = d.report_date
and t.entered_date = d.entered_date
and t.sync = d.sync;
关于php - 从 MySQL 数据库中删除重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5335381/