MySQL Query GROUP BY day / month / year

前端 未结 14 2524
野趣味
野趣味 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 06:54

    I prefer to optimize the one year group selection like so:

    SELECT COUNT(*)
      FROM stats
     WHERE record_date >= :year 
       AND record_date <  :year + INTERVAL 1 YEAR;
    

    This way you can just bind the year in once, e.g. '2009', with a named parameter and don't need to worry about adding '-01-01' or passing in '2010' separately.

    Also, as presumably we are just counting rows and id is never NULL, I prefer COUNT(*) to COUNT(id).

提交回复
热议问题