如何在一段时间后删除 MySQL 记录

How to delete a MySQL record after a certain time(如何在一段时间后删除 MySQL 记录)
本文介绍了如何在一段时间后删除 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 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)