0

Is there an MySQL query which would delete all values from a table, except the latest 20 entries (ordered by id)?

So let's say I have a table notifications, where 1000 notifications reside and I want to keep only latest 20.

If SQL is not enough for this, using php is optional.

I have a few ideas how to do this, but I don't really consider them efficient.

4

2 回答 2

0

You can find the latest id, store it into local variable and then delete everything below this id:

set @tmp_id := (select id from notifications order by id desc limit 20,1);
delete from notifications where id <= @tmp_id;
于 2012-12-04T22:51:20.517 回答
0

I have not ran this, so I apologize if it doesn't work, but according to the SQL syntax for delete this should work.

DELETE FROM notifications ORDER BY id ASC LIMIT ((SELECT COUNT(*) FROM notifications)-20);

$result = $mysqli->query("SELECT ids FROM notifications");
$count = $result->num_rows;
$count -=20;
$result = $mysqli->query("DELETE FROM notifications ORDER BY id ASC LIMIT $count");
于 2012-12-04T22:58:59.697 回答