求SQL语句。

gungod 2011-04-11 10:26:47
需求:
删除tb1数据但保留最近5条记录:

版本:
mysql 5.0.83

表tb1:
create table tb1
(
intime datetime,
txt varchar(10)
);
...全文
37 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ACMAIN_CHM 2011-04-11
  • 打赏
  • 举报
回复
[Quote]原来还有delete a from tb1 a的用法啊,[/Quote]

MySQL官方文档 http://dev.mysql.com/doc/refman/5.1/zh/index.html
ACMAIN_CHM 2011-04-11
  • 打赏
  • 举报
回复
[Quote]问下狼头大大,我这种做法是不是在tb1有大量数据量时,效率更高?[/Quote]是的,宁可TRUNCATE然后再加5条。 TRUNCATE基本上不需要时间,加五条记录也很多,但如果是删除1000条的话,显然不如你的这个方法快。
gungod 2011-04-11
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 acmain_chm 的回复:]
delete a from tb1 a left join (select intime from tb1 order by intime desc limit 5) b on a.intime=b.intime
where b.intime is null
[/Quote]

原来还有delete a from tb1 a的用法啊,

我还准备做一个临时表,把5条记录写入数据库,TRUNCATE TABLE tb1后,
再把临时表记录写入tb1;

问下狼头大大,我这种做法是不是在tb1有大量数据量时,效率更高?
wwwwb 2011-04-11
  • 打赏
  • 举报
回复
假设intime唯一

delete a from tb1 a left join (select intime from tb1 order by intime desc limit 5) b on a.intime=b.intime
where b.intime is null
ACMAIN_CHM 2011-04-11
  • 打赏
  • 举报
回复
delete a from tb1 a left join (select intime from tb1 order by intime desc limit 5) b on a.intime=b.intime
where b.intime is null

56,678

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧