我想删除“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
如何删除这些行?
答案 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);