Remove old MySQL records automatically

3

I have a table that stores logs for a system. I want some method of automatically deleting records longer than 60 days. Can you do that?

    
asked by anonymous 07.07.2016 / 21:32

1 answer

2

You can create an EVENT with your interval CURRENT_TIMESTAMP + INTERVAL 1 DAY

Here are some examples of creating events in MySQL:

CREATE EVENT 'Dropar tabela t'
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 5 DAY
DO DROP TABLE t;

This event will cause MySQL to drop the "t" table 5 days after the event was created.

CREATE EVENT O_evento_principal
ON SCHEDULE AT TIMESTAMP '2009-03-10 12:00:00'
DO DROP TABLE t;

This event will cause MySQL to drop the "t" table on March 10, 2009 at 12:00 p.m.

  

CAUTION: It is important that when an event is created with the statement   "EVERY" before the period, the task will ALWAYS be repeated in the   of a new cycle.

A "EVERY YEAR/MONTH/WEEK/DAY/HOUR/MINUTE/SECOND" statement results in a continuous execution within a ANUAL/MENSAL/SEMANAL/DIÁRIO/HORÀRIO/MINUTOS/SEGUNDOS.

For example:

CREATE EVENT e
ON SCHEDULE EVERY 1 YEAR
DO DROP TABLE t;

This event causes MySQL to drop the "t" table each year, considering the "zero" time of the event to be created.

In your case you could do

CREATE EVENT 'Delete tabela t'
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
Delete FROM tabela
WHERE TIMESTAMPDIFF(DAY, SuaData + INTERVAL TIMESTAMPDIFF(MONTH,  SuaData , current_date) MONTH , current_date) >= 60;
    
07.07.2016 / 21:59