删除mysql中的重复行,保留XX行

时间:2013-09-26 13:20:09

标签: php mysql

我想保留10个最新的重复行并删除所有其他行。

我正在使用以下代码,但它会删除除一个以外的所有记录。

DELETE FROM `history` WHERE id NOT IN (SELECT * FROM (SELECT MIN(n.id) FROM history n GROUP BY n.url) x)`

2 个答案:

答案 0 :(得分:0)

请尝试此查询

此代码将删除包含10个以上副本的所有重复行。

DELETE FROM `history` WHERE id NOT IN (
    SELECT * FROM (
        SELECT MIN(n.id) FROM history n GROUP BY n.url having count(n.url) > 10
    ) x 
)

答案 1 :(得分:0)

尝试使用此代码。

DELETE
FROM
  history
WHERE
  id NOT IN
  (SELECT
    id 
   FROM
     (
      SELECT
        @num:=IF(@current=url, @num+1, 1) AS row_num, 
        @current:=url AS group_url, 
        id
      FROM
        history
      ORDER BY
        id
     ) AS `internal`
   WHERE
     row_num<=15
  )