Mainly record the creation process of mysql events, enable, delete, view and other statements
- Take the 82 server waf_data_copy1 table as an example, create a stored procedure, delete the time (datetime) field of the table, and delete the data 60 days ago
use cloud;
DROP PROCEDURE IF EXISTS pro_clean_data;
CREATE PROCEDURE pro_clean_data()
BEGIN
DELETE FROM WAF_data_copy1 WHERE DATE(TIME) <= DATE(DATE_SUB(NOW(),INTERVAL 60 DAY));
END
Among them, TIME is the time basis for judgment.
Here is to delete data older than 60 days. If you need to delete data older than a few months, (take three months as an example) it is INTERVAL 3 MONTH.
注意一个问题,是关于mysql中BEGIN和END的坑,这个问题是查询定界符没更改导致的。如果是直接操作后台mysql进行语句编写时,
你在建立触发器之前,先执行这个语句 DELIMITER $$ ;
(这一句把原来默认的查询结尾定界符--分号 改为 $$,然后,你就可以在begin ....end 中
间 的每一句加 分号,最后在end的 后面,以$$ 作结束。 因为新的语句定界符已经是$$ 。
触发器建立后,你可以根据情况,把查询定界符$$ 改为原来的分号 , 使用 delimiter ;
mysql> DELIMITER $$
mysql> CREATE PROCEDURE pro_clean_data()
-> BEGIN
-> DELETE FROM WAF_data_copy1 WHERE DATE(TIME) <= DATE(DATE_SUB(NOW(),INTERVAL 60 DAY));
-> END$$
Query OK, 0 rows affected (0.05 sec)
mysql> DELIMITER ;
- create event
CREATE EVENT IF NOT EXISTS event_time_cleaner
ON SCHEDULE EVERY 1 DAY STARTS '2021-10-13 14:16:00'
ON COMPLETION PRESERVE
DO CALL pro_clean_data()
- Check if the event is enabled
show VARIABLES like 'event_scheduler';
- start event
set global event_scheduler=on;
建议配置文件添加相关参数,确保当数据库重启后,事件依然生效
在my.cnf中的[mysqld]部分添加,
event_scheduler=on
然后重启mysql
- 2 ways to view created events
show events;
select * from information_schema.events;
- delete event
drop event event_time_cleaner;
- View the execution results through the query statement, see