Delete N number of old records from table in mysql

此生再无相见时 提交于 2019-12-09 06:28:42

问题


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 ?


回答1:


I believe this will work...

DELETE FROM LoginTime WHERE id IN (
     SELECT id
     WHERE user_id = 1
     ORDER BY datetime DESC
     LIMIT 0, 5
)



回答2:


DELETE 
FROM LoginTime 
WHERE user_id = 1 
ORDER BY datetime ASC 
LIMIT 5



回答3:


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




回答4:


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

left join
  (
    select id
    from LoginTime
    where user_id=1
  ) as existance
on LoginTime.id=existance.id

where
  not_to_delete.id is null and existance.id is not null;


来源:https://stackoverflow.com/questions/4720996/delete-n-number-of-old-records-from-table-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!