简体   繁体   English

如果count大于20,如何从表中删除

[英]How to delete from table if count is greater than 20

I have a mysql table that I need to only contain 20 newest records before adding additional records. 我有一个mysql表,我需要在添加其他记录之前只包含20条最新记录。 New rows are added daily so I would like it first delete any records that are greater than the 20 allowed starting with the earliest. 每天都会添加新行,因此我希望首先删除任何大于最早允许的记录。

The table contains an auto increment "id" column so I can easily determine which is the earliest records. 该表包含一个自动增量“id”列,因此我可以轻松确定哪个是最早的记录。

Thanks for any help. 谢谢你的帮助。

You can specify an offset with the LIMIT keyword in your query so the newest 20 rows are kept. 您可以在查询中使用LIMIT关键字指定偏移量,以保留最新的20行。 According to MySQL's documentation, however, there's no easy way to limit from an offset all the way to the last; 然而,根据MySQL的文档,没有简单的方法可以将偏移限制为最后一个; instead, they suggest this: 相反,他们建议:

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. 要从特定偏移量检索所有行直到结果集的末尾,可以使用一些大数字作为第二个参数。

So this SQL should do the trick: 所以这个SQL应该可以解决这个问题:

DELETE FROM table ORDER BY id DESC LIMIT 20, 18446744073709551615;

With mysql 5 you cannot use an offset with on a delete statement. 使用mysql 5,您无法在删除语句中使用偏移量。 Further reading here: http://dev.mysql.com/doc/refman/5.0/en/delete.html 进一步阅读: http//dev.mysql.com/doc/refman/5.0/en/delete.html

I've managed to use the following technique to achieve preserving a set number of newest records. 我已设法使用以下技术来实现保留一定数量的最新记录。 mySQL subquery limit mySQL子查询限制

There is no offset for delete statement. delete语句没有offset Please see https://stackoverflow.com/a/8303440/2576076 , it offers a good solution. 请参阅https://stackoverflow.com/a/8303440/2576076 ,它提供了一个很好的解决方案。

Use DELETE with ORDER BY and LIMIT : 使用DELETEORDER BYLIMIT

DELETE FROM MyTable
ORDER BY MyTable.id DESCENDING
LIMIT 20,18446744073709551615;

This will leave the 20 records with the largest id and delete the rest. 这将留下具有最​​大id的20个记录并删除其余记录。

Why not to leave all records untouched? 为什么不保持所有记录不受影响?
That's the database were invented for. 这是数据库的发明。 If you want to keep only newest data, you've probably need another storage, like memcache 如果你只想保留最新的数据,你可能需要另一个存储空间,比如memcache

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM