2

I want to count the rows in several date ranges (i.e: last hour, today, this week, last 30 days) from a given table.

I need to know how many entries are in this time/date periods to be able to tell if a given user has reach the limit for each one of this ranges. For instance, a user can have max 300 entries one month but with a (hourly/daily/weekly/monthly) limit.

So far I'm trying with a subquery approach using a SELECT CASE similar to this one: group by range in mysql

Which should be the best way of doing this?

2
  • How do you currently store this information? Is it in a datetime field? You should be able to select pertinent parts using datetime functions and grouping. Providing structure for what you have and the result you want would help greatly. Commented Jun 24, 2012 at 6:31
  • yes, is stored using datetime Commented Jun 24, 2012 at 7:00

1 Answer 1

4

In mysql you could use a series of count functions with if statements so that only the required dates are counted, like so.

SELECT COUNT(IF(date >= DATE_SUB(NOW(), INTERVAL 1 HOUR), 1, null)) AS hourHits, 

and so on

Edited as per comments

Sign up to request clarification or add additional context in comments.

2 Comments

You'll want to use NULL as the false condition since COUNT() will still count 0 into its calculation, otherwise, use SUM(). Also, I believe < should be switched to > or it will count all hits that weren't within the hour.
Zane is right, this is the actual COUNT: COUNT(IF(date >= DATE_SUB(NOW(), INTERVAL 1 HOUR), 1, NULL) ) AS hourHits,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.