我有一个表,我需要将总行数保持在 50,000 以内。此表包含一个 Id 字段(id 是自动递增的)。
如何检查 if max(id) - min(id) > 50,000
,然后删除较早的行?
DELETE FROM news WHERE if (max(id) - min(id) > 50000)
如果,这query
将删除所有行max(id) - min(id) > 50000
,正确的方法是什么?理想情况下,我需要一个单行命令,以 SSH 方法为借口。谢谢。
DELETE d
FROM news AS d
JOIN
( SELECT MAX(id)-50000 AS lim
FROM news
) AS m
ON d.id < m.lim ;
当然,上述内容不会完全保留 50K 行,因为id
序列中可能存在间隙。但我想这是意料之中的,不是问题。如果您真的想保留 50K 行,那么任何语句的效率都可能会降低。你可以试试这个:
DELETE d
FROM news AS d
JOIN
( SELECT id AS lim
FROM news
ORDER BY id DESC
LIMIT 1 OFFSET 50000
) AS m
ON d.id <= m.lim ;
Delete from news where id < max(id)-50000
DELETE FROM news
WHERE id NOT IN (SELECT id FROM news ORDER BY id DESC LIMIT 50000)