简体   繁体   中英

Query database rows where timestamp column is older than X hours

I have a bunch of rows in a MySQL database table, with a last_update (TIMESTAMP) field to log when they were last modified. As of right now, I loop through all of the rows every 300 seconds and check to see if 3+ hours have elapsed, and then update that row if so.

    $update_delay = 180;

    $table_name = $wpdb->prefix . "products";
    $results = $wpdb->get_results( "SELECT id, prod_id, last_update FROM $table_name" );

    foreach ($results as $result)
    {
        $last_update = $result->last_update;

        if (time() - strtotime($last_update) > $update_delay * 60)
        {

As this is inefficient, I would like to query just the rows where the timestamp is older than 3 hours. Since that field has the format of "2020-03-01 23:22:06" I think I can do something like the following, but am not sure if I can do this using INTERVAL in the query, or if the date to check against should be in PHP.

$old_timestamp = date('Y-m-d G:i:s') . "- 3 hours";

$results = $wpdb->get_results( "SELECT id, prod_id FROM $table_name WHERE last_update > $old_timestamp" );

What would be a good option to implement this efficiently?

I would like to query just the rows where the timestamp is older than 3 hours

No need for specific application code. MySQL understands date arithmetics:

WHERE last_update > NOW() - INTERVAL 3 HOUR

Something like this?

$old_timestamp = date('Y-m-d G:i:s');
$results = $wpdb->get_results( 
    "SELECT id, prod_id FROM $table_name WHERE last_update > date_add($old_timestamp") -3 hours)
);

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