添加了多条脏数据时清理,删除重复数据

查询在表中user_id与activity_id 在 计数多余1的时候的数据并且去除ID小的,留下id大的(最新数据)
SELECT t1.id FROM 表名 t1 WHERE (t1.user_id, t1.activity_id) IN
(SELECT user_id, activity_id FROM 表名 GROUP BY user_id, activity_id HAVING COUNT() > 1)
AND t1.id NOT IN (SELECT MAX(id) FROM 表名 GROUP BY user_id, activity_id
HAVING COUNT(
) > 1)

删除时 将以上查询内容当做一张表 然后查询 该表的 要查询的内容 将该表起名 不然删除条件时,不能用in 去删除
SELECT id FROM (查询的一张表【上面查询内容】) t[并起了别名] 用来删除用
然后将这个查询内容放置于此
DELETE FROM 表名 WHERE id IN ()

完整语句
DELETE FROM 表名 WHERE id IN
(SELECT id FROM
(SELECT t1.id FROM 表名t1 WHERE (t1.user_id, t1.activity_id) IN
(SELECT user_id, activity_id FROM 表名 GROUP BY user_id, activity_id HAVING COUNT() > 1)
AND t1.id NOT IN (SELECT MAX(id) FROM 表名 GROUP BY user_id, activity_id
HAVING COUNT(
) > 1)) t)

你可能感兴趣的:(sql)