How to delete a MySQL record after a certain time

前端 未结 3 1760
渐次进展
渐次进展 2020-11-27 03:42

I want to delete some messages from my MySQL database after 7 days.

My message table rows have this format: id | message | date

The date is a timestamp in th

3条回答
  •  误落风尘
    2020-11-27 04:06

    You can try using this condition:

    WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)
    

    So that the whole SQL script looks like this:

    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;
    

    However, on your place I would solve the given problem with a simple cron script. The reasons to do this is simple: it's easier to maintain the code, no ugly SQL workarounds, integrates smoothly with your system.

提交回复
热议问题