Another neat trick you can use here is the SUM() function, which contains only the logical expression inside it. When you do this, MySQL will efficiently count the number of rows matching the condition. So using something like:
SUM(timeCol >= (NOW() - INTERVAL 1 HOUR))
It will simply count the number of rows that have a timestamp in the last hour. Try this query:
SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly, SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily, SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly FROM myTable;
This worked for me in SQL Fiddle .
EDIT
The above solution does not work if your table has future dates, so if you want you to get only values ββfor the last hour, day or month that do not exceed the current time, just add a where clause:
SELECT SUM(timecol >= (NOW() - INTERVAL 1 HOUR)) AS hourly, SUM(timeCol >= (NOW() - INTERVAL 1 DAY)) AS daily, SUM(timeCol >= (NOW() - INTERVAL 1 MONTH)) AS monthly FROM myTable WHERE timeCol <= NOW();
Here is an updated Fiddle that has an invalid entry to show that it works.
source share