MySQL MySQL选择从现在到10分钟前时间戳列的行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3480947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:51:45  来源:igfitidea点击:

MySQL Select rows where timestamp column between now and 10 minutes ago

mysqlsql

提问by krx

I have a timestamp column that auto updates on insert/update.

我有一个时间戳列,可以在插入/更新时自动更新。

I want to get the rows that have been updated within the last 10 minutes.

我想获取过去 10 分钟内更新的行。

SELECT
     *
FROM
     status
WHERE
     code='myCode'
AND
     'stamp_updated' 
     BETWEEN
     NOW()
     AND
     DATE_ADD(NOW() , INTERVAL - 10 MINUTE)
ORDER BY 
     stamp_updated DESC
LIMIT 1

回答by OMG Ponies

Use:

用:

  SELECT *
    FROM status
   WHERE code = 'myCode'
     AND `stamp_updated` BETWEEN DATE_SUB(NOW() , INTERVAL 10 MINUTE)
                           AND NOW()
ORDER BY stamp_updated DESC
   LIMIT 1

Order in the BETWEEN operator matters - you had it backwards.

BETWEEN 运算符中的顺序很重要 - 你把它倒过来了。

回答by a1ex07

 ... 'stamp_updated' BETWEEN NOW() - INTERVAL 10 MINUTE AND NOW()  ...

回答by Gregory Patmore

Not sure why you're using the between construct. MySQL can use logical operators on dates, and usually significantly faster. I would use this:

不确定为什么要使用 between 构造。MySQL 可以在日期上使用逻辑运算符,而且速度通常要快得多。我会用这个:

select * 
  from status 
  where code='myCode' 
        and stamp_updated >= DATE_SUB(NOW(), INTERVAL 10 MINUTE) 
  order by stamp_updated desc 
  limit 1;