MySQL Query GROUP BY day / month / year

前端 未结 14 2532
野趣味
野趣味 2020-11-22 06:37

Is it possible to make a simple query to count how many records I have in a determined period of time like a year, month, or day, having a TIMESTAMP field, like

14条回答
  •  日久生厌
    2020-11-22 07:10

    If your search is over several years, and you still want to group monthly, I suggest:

    version #1:

    SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
    FROM stats
    GROUP BY DATE_FORMAT(record_date, '%Y%m')
    

    version #2 (more efficient):

    SELECT SQL_NO_CACHE YEAR(record_date), MONTH(record_date), COUNT(*)
    FROM stats
    GROUP BY YEAR(record_date)*100 + MONTH(record_date)
    

    I compared these versions on a big table with 1,357,918 rows (innodb), and the 2nd version appears to have better results.

    version1 (average of 10 executes): 1.404 seconds
    version2 (average of 10 executes): 0.780 seconds

    (SQL_NO_CACHE key added to prevent MySQL from CACHING to queries.)

提交回复
热议问题