Differences in weeks between PHP and MySQL

前端 未结 1 507
暖寄归人
暖寄归人 2021-01-18 15:59

I have the following query.

SELECT COUNT(*), WEEK(date), YEAR(date) FROM myTable GROUP ON YEAR(date), WEEK(date)

Say it produces the follow

1条回答
  •  被撕碎了的回忆
    2021-01-18 16:13

    You are on the right track with regards to how MySQL works, having various modes for week-related functions that can produce different results. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week

    It is my understanding the MySQL mode which is equivalent to PHP's date logic is mode 3, which is the ISO week date standard http://en.wikipedia.org/wiki/ISO_week_date

    This has weeks starting on Mondays and weeks numbered 1-53.

    So you would need to use WEEK(date_field, 3) to get PHP compatible values.

    As an alternate approach, one thing I have found handy in cases where you need the ability to flexibly query on different date ranges or aggregations (Q1- Q4, H1 - H2, etc.), or where you might need to utilize different weeks than PHP supports is to use a date helper table in MySQL (similar to what one may use as a date dimension table in a data warehouse, if you are familiar with that). It can give you a convenient table to join against in order to look up date ranges. Something like this should work:

    http://databobjr.blogspot.com/2012/06/create-date-dimension-table-in-mysql.html

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