希望这是一个简单的解决方案,但我正在尝试过滤以下数据:-
Hopefully, it's an easy solution, but I am trying to filter the data for the following:-
我从数据库中得到的日期基本上是一个时间戳.
The date I get from the database is basically a timestamp.
这是我试过的:-
今天
SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 DAY)
昨天
Yesterday
SELECT n.title, COUNT(*) AS times FROM node_view_count WHERE timestamp > DATE_SUB(NOW(), INTERVAL 7 DAYS)
...
这真的行不通.
有什么想法吗?
如果您仅按日期选择,则根据 CURDATE
(仅返回日期)而不是 NOW 进行计算
(返回日期和时间).这些示例将捕获一天范围内的所有时间:
If you're selecting by date only, base your calculations on CURDATE
(which returns date only) rather than NOW
(which returns date and time). These examples will catch all times within the day ranges:
WHERE timestamp >= CURDATE()
WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND timestamp <CURDATE()
WHERE timestamp >= DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY)
WHERE timestamp >='2013-06-03' AND timestamp <;'2013-06-08'
本周"取决于您开始一周的哪一天;我会把它留给你.您可以使用 DAYOFWEEK
函数将 CURDATE()
调整到适当的范围.
The "this week" depends on which day you start your week; I'll leave that to you. You can use the DAYOFWEEK
function to tweak CURDATE()
to the proper ranges.
附录:OP 的列类型是 INTEGER
,存储 UNIX 时间戳,我的回答假设列类型是 TIMESTAMP
.以下是如何使用 UNIX 时间戳值执行所有相同的操作,并且如果该列被编入索引仍然保持优化(如果 TIMESTAMP
列被编入索引,上面的答案将执行)...
Addendum: OP's column type was INTEGER
, storing a UNIX timestamp, and my answer assumed the column type was TIMESTAMP
. Here's how to do all the same things with a UNIX timestamp value and still maintain optimization if the column is indexed (as the answers above will do if the TIMESTAMP
column is indexed)...
基本上,解决方案是将开始和/或结束日期包装在 UNIX_TIMESTAMP
函数:
Basically, the solution is to just wrap the beginning and/or ending dates in the UNIX_TIMESTAMP
function:
WHERE timestamp >= UNIX_TIMESTAMP(CURDATE())
WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 1 DAY)) AND timestamp <UNIX_TIMESTAMP(CURDATE())
WHERE timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL DAYOFMONTH(CURDATE())-1 DAY))
WHERE timestamp >= UNIX_TIMESTAMP('2013-06-03') AND时间戳
这篇关于从SQL中的时间戳,从今天,昨天,本周,本月和两个日期之间选择记录php mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!