MySQL:删除重复记录,同时保留最新的
问题:如何消除重复的电子邮件地址一个 MySQL 表,同时根据唯一 ID 字段保留最新的表?
解决方案:
要实现此目的,请按照以下步骤操作:
识别重复电子邮件:
使用查询检索所有重复电子邮件地址的列表:
SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1;
查找每个重复邮件的最新 ID:
使用以下查询确定与每个重复电子邮件关联的最新 ID:
SELECT MAX(id) AS lastID, email FROM test WHERE email IN ( SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1 ) GROUP BY email;
删除最旧的重复项:
执行 DELETE 操作以删除重复项ID 小于最新 ID 的电子邮件:
DELETE test FROM test INNER JOIN ( SELECT MAX(id) AS lastID, email FROM test WHERE email IN ( SELECT email FROM test GROUP BY email HAVING COUNT(*) > 1 ) GROUP BY email ) duplic ON duplic.email = test.email WHERE test.id < duplic.lastID;
优化版本:
以下优化版本提供相同的结果,同时可能提高性能:
DELETE test FROM test INNER JOIN ( SELECT MAX(id) AS lastID, email FROM test GROUP BY email HAVING COUNT(*) > 1) duplic ON duplic.email = test.email WHERE test.id < duplic.lastID;
此修订后的 DELETE 语句侧重于消除最旧的重复项。
附加选项:
或者,您可以利用 Rene Limon 提供的此查询:
DELETE FROM test WHERE id NOT IN ( SELECT MAX(id) FROM test GROUP BY email);
此方法根据最大 ID 保留最新的重复电子邮件地址。
以上是如何删除 MySQL 中重复的电子邮件地址,同时保留最新记录?的详细内容。更多信息请关注PHP中文网其他相关文章!