Deleting MySQL Records After a Specified Time with an Event
To automatically delete messages older than 7 days from a MySQL database, consider this alternative approach using an event:
CREATE EVENT delete_event ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY ON COMPLETION PRESERVE DO BEGIN DELETE messages WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY); END;
This event will execute every day, at the specified time, and delete all messages whose date column is older than 7 days.
Here's an explanation of the code:
Alternatively, you could use a cron script to perform this task. However, an advantage of using an event is that it can be configured to run independently of the system's cron scheduler.
The above is the detailed content of How Can I Automatically Delete Old MySQL Records Using Events?. For more information, please follow other related articles on the PHP Chinese website!