MySQL: Records inserted by hour, for the last 24 hours

后端 未结 1 1185
小鲜肉
小鲜肉 2021-02-10 01:42

I\'m trying to list the number of records per hour inserted into a database for the last 24 hours. Each row displays the records inserted that hour, as well as how many hours a

相关标签:
1条回答
  • 2021-02-10 02:15

    If you grouped by HOUR(time) then you should use HOUR(time) in your select expressions, and not time. For example:

    SELECT HOUR(time), COUNT(*)
    FROM `records`
    WHERE time > DATE_SUB(NOW(), INTERVAL 24 HOUR)
    GROUP BY HOUR(time)
    ORDER BY HOUR(time)
    

    Alternatively you can group by the expression you want to return:

    SELECT COUNT(*), FLOOR( TIME_TO_SEC( TIMEDIFF( NOW(), time)) / 3600 )
    FROM `records`
    WHERE time > DATE_SUB(NOW(), INTERVAL 24 HOUR)
    GROUP BY FLOOR( TIME_TO_SEC( TIMEDIFF( NOW(), time)) / 3600 )
    ORDER BY FLOOR( TIME_TO_SEC( TIMEDIFF( NOW(), time)) / 3600 )
    

    In case you were wondering, it is safe to call NOW() multiple times in the same query like this. From the manual:

    Functions that return the current date or time each are evaluated only once per query at the start of query execution. This means that multiple references to a function such as NOW() within a single query always produce the same result.

    0 讨论(0)
提交回复
热议问题