How to delete a MySQL record after a certain time(如何在一段时间后删除 MySQL 记录)
问题描述
我想在 7 天后从我的 MySQL 数据库中删除一些消息.
I want to delete some messages from my MySQL database after 7 days.
我的消息表行具有以下格式:身份证 |留言 |日期
My message table rows have this format: id | message | date
日期是普通格式的时间戳;2012-12-29 17:14:53
The date is a timestamp in the normal format; 2012-12-29 17:14:53
我认为 MySQL 事件将成为替代 cron 作业的方法.
I was thinking that an MySQL event would be the way to go instead of a cron job.
我想对有经验的 SQL 人员来说一个简单的问题,我该如何编码下面括号中的删除消息部分?
I have what I guess is a simple question to an experienced SQL person, how do I code the delete messages portion in brackets below?
一个例子将不胜感激,谢谢.
An example would be appreciated, Thanks.
DELIMITER $$
CREATE EVENT delete_event
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY
ON COMPLETION PRESERVE
DO
BEGIN
DELETE messages WHERE date >= (the current date - 7 days);
END;
$$;
推荐答案
你可以试试用这个条件:
You can try using this condition:
WHERE date < DATE_SUB(NOW(), INTERVAL 7 DAY)
让整个 SQL 脚本看起来像这样:
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;
然而,在你的地方,我会用一个简单的 cron 脚本解决给定的问题.这样做的原因很简单:代码更易于维护,没有丑陋的 SQL 变通方法,可以与您的系统顺利集成.
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.
这篇关于如何在一段时间后删除 MySQL 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在一段时间后删除 MySQL 记录


基础教程推荐
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01