[英]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.我在 MySQL 数据库表中有一堆行,有一个last_update (TIMESTAMP) 字段来记录它们上次修改的时间。 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.
截至目前,我每 300 秒遍历所有行并检查是否已过去 3 个多小时,如果是,则更新该行。
$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.由于这效率低下,我只想查询时间戳超过 3 小时的行。 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.
由于该字段的格式为“2020-03-01 23:22:06”,我想我可以执行以下操作,但不确定是否可以在查询中使用 INTERVAL 执行此操作,或者是否可以检查日期反对应该在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
我只想查询时间戳超过 3 小时的行
No need for specific application code.不需要特定的应用程序代码。 MySQL understands date arithmetics:
MySQL 理解日期算术:
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)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.