首页 > 解决方案 > MySQL:如何删除特定用户ID的所有旧记录但保留最新的3条?

问题描述

我有一个名为“令牌”的表,它存储登录到管理面板的用户的所有登录令牌。

    id  users_id    token   created_time        type        access_time
220 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-20 17:23:13
221 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-21 13:12:16
222 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-21 14:35:11
223 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-22 15:37:11
224 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-22 12:11:56
225 3       $....   2020-02-20 17:47:19 BACKOFFICE  2020-02-23 13:59:19

我存储用户的 users_id、创建令牌的时间以及访问和使用令牌的任何时间(以及其他一些位)

我的问题是,我将如何删除用户的所有 reconds,除了最近访问的 3 个?

标签: phpsql

解决方案


您可以使用row_number()join

delete t
    from tokens t join
         (select tt.*, row_number() over (partition by user_id order by access_time desc) as seqnum
          from tokens tt
         ) tt
         on tt.id = t.id
    where tt.seqnum > 3;

推荐阅读