MySQL - 仅返回过去 X 天的条目
我正在使用一个数据库,该数据库将日期信息存储为 Unix 时间戳 ( int(11) ),我想要做的只是返回过去 X 天(例如过去 90 天)的条目。
我想出的是:
SELECT * FROM mytable WHERE category=1 AND
FROM_UNIXTIME( time ) > DATE_SUB(now(), INTERVAL 91 DAY)
其中“时间”是数据库中的 int(11) 。这似乎工作正常,但只是想知道其他人对此有何看法。
I'm working with a database that has date information stored as a Unix timestamp ( int(11) ) and what I want to do is only return entries from the past X days, the past 90 days for example.
What I've come up with is:
SELECT * FROM mytable WHERE category=1 AND
FROM_UNIXTIME( time ) > DATE_SUB(now(), INTERVAL 91 DAY)
Where 'time' is the int(11) in the db. This seems to be working fine, but just wondering what others think of this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或者简单地
SELECT * FROM mytable WHERE Category=1 AND
时间> (UNIX_TIMESTAMP() - (86400*90))
这只是比较一个数字(在本例中为秒)
or simply
SELECT * FROM mytable WHERE category=1 AND
time > (UNIX_TIMESTAMP() - (86400*90))
this is just comparing a number (seconds in this case)
这个查询肯定会让你头疼,因为 MySQL 需要对每一行进行日期转换,而无法使用索引。 Unix 时间戳是数字,因此不要将时间戳转换为另一种日期格式,而是将查找日期转换为 Unix 时间戳。
This query is bound to cause you headaches down the way as MySQL needs to do the conversion of dates for every row making use of indexes impossible. Unix timestamps are numbers, so instead of converting a timestamp to another date format, convert your lookup dates to unix timestamps.
将时间戳存储为 int 的原因是什么?我会使用 mysql DATETIME 数据类型,因为您可以使用许多 日期时间函数 mysql有。
如果您无法控制该字段的数据类型,我会在执行查询之前将您的日期转换为 unix timestamp int 并以这种方式进行比较。
What is the reason for storing the timestamp as an int ? I would use the mysql DATETIME data type because you can use the many Date Time functions mysql has.
If you do not have control over the data type of this field I would convert your date to the unix timestamp int before you do your query and compare it that way.
只是大声思考......反过来做不会减少数据库的工作吗?
Just thinking aloud... wouldn't doing it the other way around cause less work for the DB?