MySQL Query GROUP BY day / month / year

前端 未结 14 2333
野趣味
野趣味 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:12

    If you want to filter records for a particular year (e.g. 2000) then optimize the WHERE clause like this:

    SELECT MONTH(date_column), COUNT(*)
    FROM date_table
    WHERE date_column >= '2000-01-01' AND date_column < '2001-01-01'
    GROUP BY MONTH(date_column)
    -- average 0.016 sec.
    

    Instead of:

    WHERE YEAR(date_column) = 2000
    -- average 0.132 sec.
    

    The results were generated against a table containing 300k rows and index on date column.

    As for the GROUP BY clause, I tested the three variants against the above mentioned table; here are the results:

    SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
    FROM date_table
    GROUP BY YEAR(date_column), MONTH(date_column)
    -- codelogic
    -- average 0.250 sec.
    
    SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
    FROM date_table
    GROUP BY DATE_FORMAT(date_column, '%Y%m')
    -- Andriy M
    -- average 0.468 sec.
    
    SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
    FROM date_table
    GROUP BY EXTRACT(YEAR_MONTH FROM date_column)
    -- fu-chi
    -- average 0.203 sec.
    

    The last one is the winner.

提交回复
热议问题