Get time interval in mysql

浪尽此生 提交于 2020-01-14 07:40:07

问题


is there a query for me to get the time interval - One minute, five minutes, quarter hour, half hour, hour, and day? I use MySQL as a database.


回答1:


to get a range, like from 30 to 45 minutes ago, do like this

SELECT * FROM tbl 
WHERE tbl.mydate > DATE(DATE_sub(NOW(), INTERVAL 45 MINUTE)) 
AND tbl.mydate < DATE(DATE_sub(NOW(), INTERVAL 30 MINUTE));



回答2:


You are probably looking for date_sub:

SELECT * FROM YOURTABLE t
WHERE t.timestamp > date_sub(NOW(), interval 1 hour);

For different intervals you can change the 1 hour to 5 days, 5 weeks, etc).

From the documentation:

DATE_SUB(date,INTERVAL expr unit)

The date argument specifies the starting date or datetime value. expr is an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.

The following table shows the expected form of the expr argument for each unit value.

unit Value     Expected expr Format

MICROSECOND    MICROSECONDS
SECOND         SECONDS
MINUTE         MINUTES
HOUR           HOURS
DAY            DAYS
WEEK           WEEKS
MONTH          MONTHS
QUARTER        QUARTERS
YEAR           YEARS


来源:https://stackoverflow.com/questions/19966123/get-time-interval-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!