Delete N number of old records from table in mysql

前端 未结 4 826
离开以前
离开以前 2021-02-10 03:26

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:56
    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

    0 讨论(0)
  • 2021-02-10 04:04

    I believe this will work...

    DELETE FROM LoginTime WHERE id IN (
         SELECT id
         WHERE user_id = 1
         ORDER BY datetime DESC
         LIMIT 0, 5
    )
    
    0 讨论(0)
  • 2021-02-10 04:09
    DELETE 
    FROM LoginTime 
    WHERE user_id = 1 
    ORDER BY datetime ASC 
    LIMIT 5
    
    0 讨论(0)
  • 2021-02-10 04:13
    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;
    
    0 讨论(0)
提交回复
热议问题