F
F
Flaker2013-12-12 19:54:45
SQL
Flaker, 2013-12-12 19:54:45

How to remove all rows from a table except the last N?

It is necessary to remove all rows from the table except for the last N pieces.
Made a request like this:

DELETE FROM `gangs_actions`
WHERE `gangs_actions_id` < (
  SELECT `gangs_actions_id` FROM `gangs_actions` 
  ORDER BY `gangs_actions_id` DESC
  LIMIT 5,1
)

But it throws an error:
You can't specify target table 'gangs_actions' for update in FROM clause
How to implement it correctly?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
O
okashirin, 2013-12-12
@Flaker

leaves the last five entries, provided the id's are in order

DELETE FROM gangs_actions
WHERE gangs_actions_id < (SELECT MAX(gangs_actions_id) - 5 FROM (SELECT * FROM gangs_actions) tmp)

and this is your request, only it will work
DELETE FROM gangs_actions
WHERE gangs_actions_id <= (
SELECT gangs_actions_id FROM (SELECT * FROM gangs_actions) as tmp
ORDER BY gangs_actions_id DESC
LIMIT 5,1
)

D
Dmitry Guketlev, 2013-12-12
@Yavanosta

What is the base?
The solution in general is a temporary table. Select in it the IDs of the objects that you want to delete, and then write a condition with a selection already from it, and not from the updated table.
For syntax, either look for yourself, or write the name of the database, I'll tell you.

L
Leagnus, 2015-10-06
@Leony

These answers are only valid if there is a PK field with numbers.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question