php - 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 个?
解决方案
您可以使用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;
推荐阅读
- c# - 导出到 wdExportFormatXPS 时,ExportAsFixedFormat 抛出异常
- bash - 从几个文件中复制字符串并将其粘贴到 bash 中的新文件中
- c++ - 缺少数组元素问题
- android - 在 HERE Lite 中等效于 HERE Starter PositioningManager
- java - 我正在尝试在 Java 中将与投注相关的组件添加到我的游戏中,但程序在要求投注金额后停止工作
- c# - 不允许访问预制对象上的 Renderer.material。改用 Renderer.sharedMaterial
- css - 使用 calc() 设置动态宽度不起作用
- python - 在 groupby pandas 函数之后导出 .csv
- visual-studio-code - NXunit 测试资源管理器未在 VS Code 上显示测试(测试资源管理器 UI)
- firebase - 有人可以帮我处理这段代码吗?Google 登录 Firebase (Flutter)