简体   繁体   English

如果时间大于4小时,则从数据库中删除

[英]Delete from database if time is greater than 4 hours

I want to delete all records in a database if the timestamp is older than 4 hours. 如果时间戳早于4个小时,我想删除数据库中的所有记录。

So my logic is to get the hour of the current time and get the hour of from the timestamp saved in the database and subtract to see if it is greater than 4. If it is greater than 4 than delete the records. 所以我的逻辑是获取当前时间的小时数,并从保存在数据库中的时间戳中获取小时数,然后减去以查看是否大于4。如果大于4,则删除记录。

This is a code work in progress not really sure if it is correct. 这是一个正在进行的代码工作,不确定是否正确。

DELETE FROM posts
WHERE id IN 
   (SELECT *
    FROM posts
    WHERE (HOUR(CURRENT_TIMESTAMP) - HOUR(time_published)) > 4)
   )

if it makes a difference I am using MySQL. 如果有所作为,我正在使用MySQL。

Why not a simple 为什么不简单

delete 
from posts 
where timestampdiff(hour, current_timestamp, time_published)>=4

Note that comparing the hour portions of date fields won't do what you expect. 请注意,比较日期字段的小时部分不会达到您的期望。 Consider comparing 21st Jan 1985 10:00 and 22nd Jan 1985 11:00 . 考虑比较21st Jan 1985 10:0022nd Jan 1985 11:00 21st Jan 1985 10:00 22nd Jan 1985 11:00 Your original condition would fail (1 hour), but it's actually 25 hours between them. 您的原始条件会失败(1小时),但实际上间隔了25小时。

If you save the record at timestamp 1:00' and run this query at 5:59' nothing will be removed because the time difference is 4:59' and the hour component of that is 4! 如果您将记录保存在时间戳1:00'并在5:59'运行此查询,则不会删除任何内容,因为时差为4:59',小时部分为4! It might be what you want but that's way closer to 5 hours than 4. Assuming that minutes are your smallest unit of precision, you might want to do something like 这可能是您想要的,但是比4少了5个小时。假设分钟是最小的精度单位,则可能需要执行以下操作

DELETE FROM posts
WHERE TIMESTAMPDIFF(MINUTE, CURRENT_TIMESTAMP, time_published) > 240

And use nested queries only when they are absolutely necessary; 并且仅在绝对必要时才使用嵌套查询; they possibly could slow your operations down drastically. 他们可能会大大降低您的操作速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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