如何删除除最新的50之外的所有行

时间:2011-08-29 08:00:02

标签: mysql database

我如何删除表recentposts

中的所有行
DELETE FROM recentposts WHERE recentposts.`userId` = 12 AND recentposts.`Id` 
NOT IN (SELECT * FROM recentposts WHERE `userId` = 12 ORDER BY viewdate LIMIT 50)

我尝试了许多类似于此的但他们没有奏效。谁能告诉我如何在Mysql中做到这一点。

2 个答案:

答案 0 :(得分:3)

这个怎么样?

DELETE FROM recentposts
WHERE
    recentposts.`userId` = 12
    AND
    recentposts.`Id` NOT IN (SELECT Id
        FROM recentposts
        WHERE `userId` = 12
        ORDER BY viewdate DESC LIMIT 50)

答案 1 :(得分:2)

DELETE FROM `recentpost`
WHERE WHERE userId = 12 AND id NOT IN (
  SELECT id
  FROM (
    SELECT id
    FROM `table`        
    ORDER BY id DESC
    LIMIT 50
  ) foo
);

PS:仅在早期版本中工作(MySQL 5.0.67及更高版本)AS这些是MySQL的限制。

  • 您不能在同一查询中从给定表中删除和SELECT。
  • MySQL不支持子查询中的LIMIT。

所以对于以前的版本,你可以想出的是分两个阶段来完成:

第一步

SELECT id FROM mytable ORDER BY id DESC LIMIT n;

收集id并将它们组成逗号分隔的字符串:

DELETE FROM mytable WHERE id NOT IN ( ...comma-separated string... );