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
Counting rows where a timestamp is less than 24 hours old
提问by John
For the query below, how could I count the number of rows where datesent
is less than 24 hours old? (The field datesent
is 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
回答by Suirtimed
$message="select count(1)
from privatemessage
where datesent>=date_sub(now(), 24 hours)
and recipient='$u'"
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
回答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))