MySQL 计算时间戳小于 24 小时的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4541205/
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 18:07:20  来源:igfitidea点击:

Counting rows where a timestamp is less than 24 hours old

mysqltimestamp

提问by John

For the query below, how could I count the number of rows where datesentis less than 24 hours old? (The field datesentis a timestamp).

对于下面的查询,我如何计算datesent不到 24 小时的行数?(该字段datesent是时间戳)。

Thanks in advance,

提前致谢,

John

约翰

  $message = "SELECT datesent, recipient
               FROM privatemessage 
              WHERE recipient = '$u'";


  $messager = mysql_query($message);

$messagearray = array(); 

回答by OMG Ponies

Use:

用:

SELECT COUNT(*) AS cnt
  FROM PRIVATEMESSAGE pm
 WHERE pm.datesent >= DATE_SUB(NOW(), INTERVAL 1 DAY)

回答by Suirtimed

You can use the DATE_SUBfunction. Subtract one day from the current date in the where clause.

您可以使用DATE_SUB函数。从 where 子句中的当前日期减去一天。

Something like

就像是

DATE_SUB(NOW(), INTERVAL 1 DAY)

EDIT: changed CURTIME() to NOW()

编辑:将 CURTIME() 更改为 NOW()

回答by Suirtimed

回答by Daniel Mellum

I see this is a old one though for anybody that gets here trough an online search later on, I would like to clarify that the question is about a timestamp, not datetime. I needed a count based on timestamp. Easy fix is to convert the datetime to unix_timestamp. Tested on MySQL 5.7

我看到这是一个旧的,但对于稍后通过在线搜索到达这里的任何人,我想澄清一下问题是关于时间戳,而不是日期时间。我需要一个基于时间戳的计数。简单的解决方法是将日期时间转换为 unix_timestamp。在 MySQL 5.7 上测试

SELECT COUNT(*) AS cnt
FROM PRIVATEMESSAGE pm
WHERE pm.datesent >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))