MySQL删除除最新的X记录之外的所有内容

时间:2012-01-16 20:44:40

标签: mysql sql-delete records

我有一个脚本在我的php网站上每小时运行一次。在那个脚本中,我想要某种MySQL查询来删除表中的每条记录但是说最新的50。

我该怎么做?

// pseudo code: like this?
DELETE from chat WHERE id = max (ID - 50) 

3 个答案:

答案 0 :(得分:16)

您可以尝试使用NOT IN:

编辑 MySQL

DELETE FROM chat WHERE id NOT IN ( 
  SELECT id 
  FROM ( 
    SELECT id 
    FROM chat 
    ORDER BY id DESC 
    LIMIT 50
  ) x 
); 

这适用于 SQL-Server

DELETE FROM chat WHERE id NOT IN 
    (SELECT TOP 50 id FROM chat ORDER BY id DESC)  

假设id的更高值总是更新。

答案 1 :(得分:2)

NOT IN效率低下。您可以稍微修改@Mithrandir上一个答案中的第一个选项,使其如下所示:

DELETE from chat WHERE id < 
  (SELECT id FROM 
    (SELECT id FROM chat ORDER BY id DESC LIMIT 50) t ORDER BY id ASC LIMIT 1));

答案 2 :(得分:0)

您可以尝试这样的事情:

DELETE from chat WHERE id < (SELECT max(ID)-50 FROM chat) 

如果您的ID值以1为增量递增,则可以使用。或者您可以使用以下内容:

DELETE FROM chat WHERE id NOT IN 
    (SELECT id FROM ( SELECT ID FROM chat ORDER BY datetime_col DESC LIMIT 50) t ) -- mysql