在MYSQL中自动删除超过7天的行的存储过程

Kei*_*Wai 1 mysql linux automation stored-procedures

我想知道是否可以创建一个存储过程,每天在00:00自动删除每个超过7天的表的每一行.

我见过很少的解决方案,但不确定它是否正在寻找,如果有人有任何好的例子,那就太好了.我知道这可以通过python和php中的简单脚本来完成,但我想通过MySQL更自动化的东西.

任何帮助都会非常感激.

谢谢!

Dre*_*rew 8

当您调度的大部分内容与sql相关且文件相关性较低时,Mysql具有EVENT功能,可以避免复杂的cron交互.请参见此处的手册页.希望以下内容可以快速概述要考虑的重要步骤和事项,以及可验证的测试.

show variables where variable_name='event_scheduler';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| event_scheduler | OFF   |
+-----------------+-------+
Run Code Online (Sandbox Code Playgroud)

ooops,事件调度程序未打开.什么都不会触发.

SET GLOBAL event_scheduler = ON; -- turn her on and confirm below

show variables where variable_name='event_scheduler';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| event_scheduler | ON    |
+-----------------+-------+
Run Code Online (Sandbox Code Playgroud)

用于测试的模式

create table theMessages
(   id int auto_increment primary key,
    userId int not null,
    message varchar(255) not null,
    updateDt datetime not null,
    key(updateDt)
    -- FK's not shown
);
-- it is currently 2015-09-10 13:12:00
-- truncate table theMessages;
insert theMessages(userId,message,updateDt) values (1,'I need to go now, no followup questions','2015-08-24 11:10:09');
insert theMessages(userId,message,updateDt) values (7,'You always say that ... just hiding','2015-08-29');
insert theMessages(userId,message,updateDt) values (1,'7 day test1','2015-09-03 12:00:00');
insert theMessages(userId,message,updateDt) values (1,'7 day test2','2015-09-03 14:00:00');
Run Code Online (Sandbox Code Playgroud)

创建2个活动,每天第1次,每10分钟第2次

忽略他们实际在做什么(互相对战).重点是time difference方法和时间安排.

DELIMITER $$
CREATE EVENT `delete7DayOldMessages`
  ON SCHEDULE EVERY 1 DAY STARTS '2015-09-01 00:00:00'
  ON COMPLETION PRESERVE
DO BEGIN
   delete from theMessages 
   where datediff(now(),updateDt)>6; -- not terribly exact, yesterday but <24hrs is still 1 day
   -- etc etc all your stuff in here
END;$$
DELIMITER ;
Run Code Online (Sandbox Code Playgroud)

...

DELIMITER $$
CREATE EVENT `Every_10_Minutes_Cleanup`
  ON SCHEDULE EVERY 10 MINUTE STARTS '2015-09-01 00:00:00'
  ON COMPLETION PRESERVE
DO BEGIN
   delete from theMessages 
   where TIMESTAMPDIFF(HOUR, updateDt, now())>168; -- messages over 1 week old (168 hours)
   -- etc etc all your stuff in here
END;$$
DELIMITER ;
Run Code Online (Sandbox Code Playgroud)

显示事件状态(不同方法)

show events from so_gibberish; -- list all events by schema name (db name)
show events; -- <--------- from workbench / sqlyog
show events\G;` -- <--------- I like this one from mysql> prompt

*************************** 1. row ***************************
                  Db: so_gibberish
                Name: delete7DayOldMessages
             Definer: root@localhost
           Time zone: SYSTEM
                Type: RECURRING
          Execute at: NULL
      Interval value: 1
      Interval field: DAY
              Starts: 2015-09-01 00:00:00
                Ends: NULL
              Status: ENABLED
          Originator: 1
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
*************************** 2. row ***************************
                  Db: so_gibberish
                Name: Every_10_Minutes_Cleanup
             Definer: root@localhost
           Time zone: SYSTEM
                Type: RECURRING
          Execute at: NULL
      Interval value: 10
      Interval field: MINUTE
              Starts: 2015-09-01 00:00:00
                Ends: NULL
              Status: ENABLED
          Originator: 1
character_set_client: utf8
collation_connection: utf8_general_ci
  Database Collation: utf8_general_ci
2 rows in set (0.06 sec)
Run Code Online (Sandbox Code Playgroud)

随机的东西要考虑

drop event someEventName; - <-----了解一件好事

不能别名为datediff并在1行中的where子句中使用,所以

select id,DATEDIFF(now(),updateDt) from theMessages where datediff(now(),updateDt)>6;
Run Code Online (Sandbox Code Playgroud)

更确切地说,1周大168小时

select id,TIMESTAMPDIFF(HOUR, updateDt, now()) as `difference` FROM theMessages;
+----+------------+
| id | difference |
+----+------------+
|  1 |        410 |
|  2 |        301 |
|  3 |        169 |
|  4 |        167 |
+----+------------+
Run Code Online (Sandbox Code Playgroud)

手册页的链接显示了间隔选择的相当多的灵活性,如下所示:

间隔:

quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
          WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |
          DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}
Run Code Online (Sandbox Code Playgroud)

并发

嵌入任何必要的并发度量,多个事件(或同一事件的多次触发)不会导致数据无法运行.

设置并忘记

记住,现在,因为你会忘记它,这些事件只会继续发射.因此,即使您忘记了,也要构建能够保持运行的可靠代码.你最有可能的.

你的特殊要求

You need to determine which rows need to be deleted first by table, such that it honors Primary Key constraints. Just lump them all in proper order inside of the obvious area via the CREATE EVENT statement, which can be massive.