duanlai1855 2012-12-04 22:41
浏览 37
已采纳

从SQL表中删除除了最后X个条目以外的所有内容?

Is there an MySQL query which would delete all values from a table, except the latest 20 entries (ordered by id)?

So let's say I have a table notifications, where 1000 notifications reside and I want to keep only latest 20.

If SQL is not enough for this, using php is optional.

I have a few ideas how to do this, but I don't really consider them efficient.

  • 写回答

2条回答 默认 最新

  • drwo32555 2012-12-04 22:51
    关注

    You can find the latest id, store it into local variable and then delete everything below this id:

    set @tmp_id := (select id from notifications order by id desc limit 20,1);
    delete from notifications where id <= @tmp_id;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100