Delete N number of old records from table in mysql

前端 未结 4 1951
攒了一身酷
攒了一身酷 2021-02-10 03:25

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             


        
4条回答
  •  你的背包
    2021-02-10 03:57

    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;
    

提交回复
热议问题