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.
Asked
Active
Viewed 2.1k times
11
-
1what do you mean "get the time interval". what do the tables look like – AwokeKnowing Nov 13 '13 at 22:52
-
they probably mean... "2 days ago" or something – gloomy.penguin Nov 13 '13 at 22:54
-
yea like that, like an hour ago, what are the values an hour ago. like that. on the table i have the id, timestamp, and then the value – hearmeroar Nov 13 '13 at 23:01
2 Answers
12
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));

AwokeKnowing
- 7,728
- 9
- 36
- 47
-
You need to remove DATE() from the Where clause otherwise it doesn't do minute ranges it just does the days. I know this is from years ago, but I was trying to find why this wasn't working for me, and may benefit others using this answer in their own code – schofs May 25 '17 at 13:12
7
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

Filipe Silva
- 21,189
- 5
- 53
- 68