简体   繁体   中英

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. 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.

Thanks for any help.

You can specify an offset with the LIMIT keyword in your query so the newest 20 rows are kept. According to MySQL's documentation, however, there's no easy way to limit from an offset all the way to the last; 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:

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

With mysql 5 you cannot use an offset with on a delete statement. Further reading here: 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

There is no offset for delete statement. Please see https://stackoverflow.com/a/8303440/2576076 , it offers a good solution.

Use DELETE with ORDER BY and LIMIT :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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