Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL DATETIME DIFF query

I have a MySQL query that runs via cron every 30 minutes to delete old property listings, the query is:

 DELETE FROM $wpdb->posts WHERE post_type = 'rentals' AND DATEDIFF(NOW(), post_date_gmt) >=2  

right now its in a testing phase and set to delete when the listing is 2 days old, this it does without a problem, the problem that i do have is that i need it to recognise the time from when the listing was posted and the time to when it should be deleted,

Basically the table column of post_date_gmt is in the format of 2011-05-26 13:10:56 and the column type is DATETIME when i have the DATEDIFF (NOW() query running it needs to be equal to 48 hours or more from current time to delete the listing, this is not happening, the query just seems to say "this is the 2nd day, delete listing" so it gets deleted and this could be when just 24 and a half hours old, how can i make it go the full exact 48 hours?

Regards

like image 781
MartinJJ Avatar asked Jun 20 '11 11:06

MartinJJ


People also ask

How can I get the difference between two timestamps in MySQL?

To calculate the difference between the timestamps in MySQL, use the TIMESTAMPDIFF(unit, start, end) function. The unit argument can be MICROSECOND , SECOND , MINUTE , HOUR , DAY , WEEK , MONTH , QUARTER , or YEAR .

How do I subtract one date from another in MySQL?

DATE_SUB() function in MySQL is used to subtract a specified time or date interval to a specified date and then returns the date.

How does MySQL calculate duration?

MySQL TIMEDIFF() Function The TIMEDIFF() function returns the difference between two time/datetime expressions. Note: time1 and time2 should be in the same format, and the calculation is time1 - time2.

How do you find the difference between two timestamps?

If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.


1 Answers

Try timediff with a 48 hours delta instead . Or use a 3 days delta if precision is not an issue.

Try HOUR(TIMEDIFF(NOW(), date))

SELECT count(*) FROM $wpdb->posts WHERE post_type = 'rentals' AND HOUR(TIMEDIFF(NOW(),  post_date_gmt)) >=48

There is a lot of MySQL date/time function : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_hour

Note: use SELECt before trying DELETE

like image 81
VGE Avatar answered Sep 24 '22 15:09

VGE