MySQL数据库定时任务,在一个表中,每1小时定时删除每个用户较早的数据,只保留最新的10条记录
数据库表详情看附图,表中存储多个用户的记录,search_time表示该条记录插入数据库的时间...
数据库表详情看附图,表中存储多个用户的记录,search_time表示该条记录插入数据库的时间
展开
1个回答
展开全部
写个脚本 用crontab设置每小时执行一次,SQL语句如下:
delete from tbname order by search_time desc limit 11,1000
如果数据超过1000可以再大点。
delete from tbname order by search_time desc limit 11,1000
如果数据超过1000可以再大点。
更多追问追答
追问
你说的是一个用户的情况,这个表是保存了多个用户的记录,我不知道怎么实现对应的每个用户删除较早的记录,只保留最新10条
追答
试试
delete from tbname where id not in (select id
from tbname as a1
inner join (select a.u_id
from article as a
left join article as b
on a.u_id = b.u_id
and a.search_time <= b.search_time
group by a.u_id,a.search_time
having count(b.search_time) <= 10
) as b1 on a1.u_id = b1.u_id and a1.search_time = b1.search_time
order by a1.u_id,a1.search_time desc
)
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询