基于3列匹配的值,删除mysql中的重复项

时间:2014-09-25 20:03:44

标签: mysql

我在下面的查询显示了我的表中的重复项。我想知道如何将其转换为删除查询以删除这些重复行但只留下一行。我的表有一个自动增量id列。

SELECT * FROM tbl_user_tmp AS t1
INNER JOIN (
SELECT name, activity, class, COUNT(1) AS cnt FROM tbl_user_tmp
WHERE user = 'test' AND disregard = 0
GROUP BY name, activity, class
HAVING cnt > 1
) AS t2
ON t1.name = t2.name AND t1.activity = t2.activity AND t1.class = t2.class

WHERE user = 'test' AND disregard = 0
GROUP BY t1.name, t1.activity, t1.class

我已经尝试了下面的查询,似乎工作,但我害怕我错过了一些东西。它看起来是否正确?

delete from tbl_user_tmp 
where user='test' AND id not in
(
      select minid from 
      (select min(id) as minid from tbl_user_tmp where user='test' group by name, activity, class) as newtable
)

1 个答案:

答案 0 :(得分:0)

您可以使用LIMIT。 例如:

DELETE FROM users
LIMIT 2;

现在您只需将COUNT - 1设置为限制;)