MySQL 删除除最新 X 记录之外的所有记录
我有一个每小时在我的 php 网站上运行的脚本。在该脚本中,我想要某种 MySQL 查询来删除表中的每条记录,但要删除最新的 50 条记录。
我该如何做类似的事情呢?
// pseudo code: like this?
DELETE from chat WHERE id = max (ID - 50)
I have a script that runs every hour on my php site. In that script I would like some kind of MySQL query to delete every record from a table but say the latest 50.
How would I do something like that?
// pseudo code: like this?
DELETE from chat WHERE id = max (ID - 50)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试使用 NOT IN:
EDIT for MySQL:
这适用于 SQL-Server:
假设较高的
id
值始终较新。You could try using NOT IN:
EDIT for MySQL:
This is for SQL-Server:
Assuming higher values of
id
are always newer.NOT IN 效率低下。您可以稍微修改@Mithrandir 之前的答案中的第一个选项,使其看起来像这样:
NOT IN is inefficient. You can slightly modify the first option in the previous answer by @Mithrandir to make it look like this:
您可以尝试这样的操作:
如果您的 ID 值以 1 为步长递增,则这会起作用。或者您可以使用类似以下内容的操作:
You could try something like this:
This would work if your values for ID are incremented in steps of 1. Or you can use something like: