MySQL - 仅返回过去 X 天的条目

发布于 2024-08-02 05:24:05 字数 282 浏览 2 评论 0原文

我正在使用一个数据库,该数据库将日期信息存储为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

远山浅 2024-08-09 05:24:05
SELECT * FROM mytable WHERE category=1 AND 
time > (UNIX_TIMESTAMP() - ((60*60*24)*90))

或者简单地

SELECT * FROM mytable WHERE Category=1 AND
时间> (UNIX_TIMESTAMP() - (86400*90))

这只是比较一个数字(在本例中为秒)

SELECT * FROM mytable WHERE category=1 AND 
time > (UNIX_TIMESTAMP() - ((60*60*24)*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)

梦幻的味道 2024-08-09 05:24:05

这个查询肯定会让你头疼,因为 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.

稍尽春風 2024-08-09 05:24:05

将时间戳存储为 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.

夜巴黎 2024-08-09 05:24:05

只是大声思考......反过来做不会减少数据库的工作吗?

time > UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 91 DAY) )

Just thinking aloud... wouldn't doing it the other way around cause less work for the DB?

time > UNIX_TIMESTAMP( DATE_SUB(NOW(), INTERVAL 91 DAY) )
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文