我正在使用此SQL语句查找重复记录:
SELECT id,
user_id,
activity_type_id,
source_id,
source_type,
COUNT(*) AS cnt
FROM activities
GROUP BY id, user_id, activity_type_id, source_id, source_type
HAVING COUNT(*) > 1
但是,我不仅要查找,还要删除相同的操作。
答案 0 :(得分:1)
delete from activities where id not in (select max(id) from activities group by ....)
感谢@OMG小马和他在这里的其他帖子是修改后的解决方案(但不完全一样)。我在这里假设哪个特定行未被删除无关紧要。还假设id
是主键。
在我的示例中,我只是设置了一个额外的列name
进行测试,但可以通过GROUP BY子句轻松扩展到更多列。
DELETE a FROM activities a
LEFT JOIN (SELECT MAX(id) AS id FROM activities GROUP BY name) uniqId
ON a.id=uniqId.id WHERE uniqId.id IS NULL;