Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete N number of old records from table in mysql

I have a LoginTime table like this:

id | user_id | datetime
1  |   1     | 2011-01-19 18:51:01
2  |   1     | 2011-01-19 18:51:02  
3  |   1     | 2011-01-19 18:51:03  
4  |   1     | 2011-01-19 18:51:04  
5  |   1     | 2011-01-19 18:51:05  
6  |   1     | 2011-01-19 18:51:06  
7  |   1     | 2011-01-19 18:51:07  
8  |   1     | 2011-01-19 18:51:08  
9  |   1     | 2011-01-19 18:51:09  
10 |   2     | 2011-01-19 18:51:10  

I want to keep only 5 latest(by 'datetime' column) records and delete all previous records where user_id=1

Is it possible to achieve this with one mysql query ?

like image 761
Awan Avatar asked Jan 18 '11 06:01

Awan


3 Answers

DELETE 
FROM LoginTime 
WHERE user_id = 1 
ORDER BY datetime ASC 
LIMIT 5
like image 113
andrii Avatar answered Nov 16 '22 19:11

andrii


I believe this will work...

DELETE FROM LoginTime WHERE id IN (
     SELECT id
     WHERE user_id = 1
     ORDER BY datetime DESC
     LIMIT 0, 5
)
like image 29
jocull Avatar answered Nov 16 '22 17:11

jocull


delete LoginTime
from 
  LoginTime
left join
  (
    select id
    from LoginTime
    where user_id=1
    order by `datetime` desc
    limit 5
  ) as not_to_delete
on LoginTime.id=not_to_delete.id
where
  not_to_delete.id is null;

PS: please don't use CamelCase for table name, and avoid using reserved keywords for the column name

like image 2
ajreal Avatar answered Nov 16 '22 19:11

ajreal