L
L
lightalex2016-06-16 17:47:25
PHP
lightalex, 2016-06-16 17:47:25

How to delete all records except the newest MySQL?

Hello colleagues!
There is a table with user and date columns
Tell me how to delete all records except the 6 most recent (by date) for user=n?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AlexeyVD, 2016-06-17
@AlexeyVD

DELETE t
  FROM table1 t
  JOIN (SELECT MIN(date) AS min_date
             FROM (SELECT date
                           FROM table1 
                           WHERE user = n
                           ORDER BY date DESC 
                           LIMIT 6) t1
        ) sel ON t.date < sel.min_date
  WHERE sel.user = n;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question