简体   繁体   中英

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.

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.

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.

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 . Your original condition would fail (1 hour), but it's actually 25 hours between them.

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! 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

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.

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