从mysql中的表中删除N条旧记录

时间:2011-01-18 06:09:05

标签: mysql sql sql-delete

我有一个 LoginTime 表,如下所示:

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  

我想只保留5个最新(按'日期时间'列)的记录,并删除user_id=1

之前的所有记录

是否可以通过一个mysql查询实现此目的?

4 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:4)

我相信这会奏效......

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

答案 2 :(得分:2)

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:请不要将CamelCase用于表名,并避免使用保留关键字作为列名

答案 3 :(得分:0)

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;