MySQL count rows in multiple date ranges?

冷暖自知 提交于 2019-12-13 15:56:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/11175427/mysql-count-rows-in-multiple-date-ranges

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