我有一张表,我需要将总行数保持在50,000以内。该表包含Id字段(id为自动增量)。
如何查看是否max(id) - min(id) > 50,000
,然后删除之前的行?
DELETE FROM news WHERE if (max(id) - min(id) > 50000)
如果query
,此max(id) - min(id) > 50000
会删除所有行,这是正确的方法吗?理想情况下,我需要一个单行命令,借口用SSH方法。感谢。
答案 0 :(得分:4)
DELETE d
FROM news AS d
JOIN
( SELECT MAX(id)-50000 AS lim
FROM news
) AS m
ON d.id < m.lim ;
由于id
序列中可能存在间隙,因此上述内容当然不会留下50K行。但我想这是预料而不是问题。如果你真的想要留下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 ;
答案 1 :(得分:2)
Delete from news where id < max(id)-50000
答案 2 :(得分:2)
DELETE FROM news
WHERE id NOT IN (SELECT id FROM news ORDER BY id DESC LIMIT 50000)