实际项目中只想将最近7天的记录保存在mysql数据库中,使用程序通过sql指令的方式删除比较麻烦且效率低,用mysql 提供的事件调度器
实际项目中只想将最近7天的记录保存在mysql数据库中,使用程序通过sql指令的方式删除比较麻烦且效率低,,用mysql 提供的事件调度器(event scheduler)可轻松实现。
具体步骤如下:
1:超级用户方式登陆mysql console
# mysql -uroot
2:打开event_scheduler(默认是关掉的)
mysql> set global event_scheduler = on;
3:创建我们的事件(本例中命名为delete_old_record)
mysql> create event delete_old_record
on schedule every 1 day starts now()
do
-- delete the old records of demo_1_table
delete from demo_1_table where datediff(now(),log_timestamp)>=7;
-- delete the old records of puma_2_table
delete from demo_2_table where datediff(now(),log_timestamp)>=7;
-- delete the old records of puma_3_table
delete from demo_3_table where datediff(now(),log_timestamp)>=7;
-- delete the old records of puma_4_table
delete from demo_4_table where datediff(now(),log_timestamp)>=7;
4:启动创建的事件
mysql> alter event delete_old_record enable;
这样以后,数据库就会每天执行do后面的作业,删除各个table中7天之前的记录。
附录:create event的格式如下:
create
[definer = { user | current_user }]
event
[if not exists]
event_name
on schedule schedule
[on completion [not] preserve]
[enable | disable | disable on slave]
[comment 'comment']
do event_body;
schedule:
at timestamp [+ interval interval] ...
| every interval
[starts timestamp [+ interval interval] ...]
[ends timestamp [+ interval interval] ...]
interval:
quantity {year | quarter | month | day | hour | minute |
week | second | year_month | day_hour | day_minute |
day_second | hour_minute | hour_second | minute_second}