简体   繁体   中英

a job to delete rows older than 3 months in mysql database

We use mysql server as a centralized logging system and I want to have a job to delete\\clean the table entries that are more than 3 months old regularly. What is the best way to do this?

Thanks in advance.

-hinling

Do you store the date an item is created in a field?

If so,

DELETE FROM myTable WHERE dateEntered < DATE_SUB(NOW(), INTERVAL 3 MONTH);

should work...

You could run it in a scheduled task/cron job...

MySQL 5.1 supports Events . I haven't actually used them myself, so I won't vouch for them. However, if all you want to do is to run a DELETE statement on a regular basis, I think that it would work well enough.

A simple way would be to scheduled a job that runs every night that calls a stored procedure to delete all rows older than three months. Depending on your O/S it should be easy to do. Do it each night and the amount of deleted data won't be as much as doing it once a month or so.

I have also in the past, had code in my SP that inserted data to do the deletes of unneeded data at that time, so basically every time a row is inserted, right after the insert in ran a 'cleanup' proc that did a bit of maintenance. This wouldn't be my first choice, but its doable if the number of inserts is low, and the deletes can be done fast (you don't want to slow the user down). Nice side-effect of this is the data is always clean (ie all data is always <= 3 months old), but not sure if that matters in your app.

You should also consider archiving the rows to another table instead in addition to deleting them, if there is any chance you might want the data someday for another purpose. I always do this, and you'd be surprised what a hero you can look like when some manager who doesn't even know you are saving the data, suddenly has an urgent need for it....and you can deliver for them.

解释你的问题,“我的代码不依赖于客户端,我想多次在数据库上运行,而且我不需要看输出”,那么答案是“编写存储过程,并且从任何客户定期拨打电话“。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM