删除除前20个新行之外的所有旧行

时间:2011-10-31 22:12:18

标签: mysql sql-delete

我想删除“idx_links”表中的所有旧行,除了最新的20个。 pubDate是时间戳。

此选择带来行:

SELECT @row := @row + 1 AS row, t.*
FROM idx_links t, (SELECT @row := 0) r
having(row>20)
ORDER BY pubDate DESC

如何删除这些行?

1 个答案:

答案 0 :(得分:3)

这个怎么样 - 删除pubDate除前20名以外的所有行。

 DELETE idx_links
 WHERE ID NOT IN (SELECT ID FROM idx_links 
                  ORDER BY pubDate DESC LIMIT 0,20);

或者按日期,并避免IN子句的子查询:

DELETE idx_links
WHERE pubDate < (SELECT pubDate FROM idx_links 
                 ORDER BY pubDate DESC LIMIT 20,1);