我有一个表(名为 tasks
),其列 created_at
基本上包含 UNIX 时间戳。
我只需要选择在指定时间间隔内创建的那些结果。
间隔为今天
、明天
、本周
和本月
。
我认为如果我将时间戳转换为 YYYY-MM-DD HH:MM:SS 格式,MySQL 可以处理它。
另外,我认为我也需要在那里使用 BETWEEN
。
因此,我传递时间戳来查询并比较(检查?)它是否在指定的时间间隔内与存储在数据库中的时间戳。要进行转换,我需要使用 FROM_UNIXTIME
,对吧?
如何指定这些间隔?谢谢指教!
I have table (named tasks
) with column created_at
that, basically, contains UNIX time-stamp.
I need to select only those results that are created in specified time-interval.
Intervals are today
, tomorrow
, this week
and this month
.
I think that if I convert time-stamp to YYYY-MM-DD HH:MM:SS
format, MySQL can handle it.
Also, I think that I need to use BETWEEN
there as well.
So, I pass time-stamp to query and compare (check?) that it's in the specified interval with time-stamp that is stored in the database. To convert, I need to use FROM_UNIXTIME
, right?
How to specify those intervals? Thanks in an advice!
发布评论
评论(2)
您需要转换 UNIX_TIMESTAMP。
查询
您可以通过执行以下操作来更改周、月等的间隔:
MySQL 将自动考虑月份和闰年等的长度。
在上面的查询中,MySQL 将能够使用索引,从而大大加快速度。
确保不要在您的列上使用函数,因为在这种情况下,MySQL 无法在该字段上使用索引,从而导致速度显着降低。
编码恐怖,非常慢
请参阅:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
You need to convert UNIX_TIMESTAMP.
Query
You can alter the interval for week, month etc by doing:
MySQL will automatically take the length of months and leap years etc into account.
In the above query MySQL will be able to use an index, speeding things up a lot.
Make sure not to use a function on your column, because in that case MySQL cannot use an index on that field, causing major slowness.
Coding horror, very slow
See: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
我猜created_at被定义为INT并且你在其中存储时间戳。那么,比如说今天,最好的方法是:
created_at BETWEEN UNIX_TIMESTAMP(CURDATE()) AND UNIX_TIMESTAMP(CURDATE() + INTERVAL 1 DAY)
请注意,以下内容也适用:
FROM_UNIXTIME (created_at) BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 DAY)
,但是你可能没有机会让 MySQL 使用列索引。对于周/月,您需要使用 WEEK() 和 MONTH() 内置函数的更复杂的逻辑(以获取当前周/月第一秒的时间戳)。
I guess created_at is defined as INT and you store timestamps in it. Then the best way for, say, today, would be:
created_at BETWEEN UNIX_TIMESTAMP(CURDATE()) AND UNIX_TIMESTAMP(CURDATE() + INTERVAL 1 DAY)
Note the below will also work:
FROM_UNIXTIME(created_at) BETWEEN CURDATE() AND (CURDATE() + INTERVAL 1 DAY)
, but you'll probably have no chances to make MySQL use column indexes. For week/month you'll need a more complex logic with WEEK() and MONTH() built-in functions (to get the timestamp of the first second of the current week/month).