根据ISO 标准,一年中的第 1 周是起始年中大部分天数的第一周,而week(date,1)
为“2012-12-31”返回第 53 周,或者根据此week(date,3)
等值weekofyear(date)
正确返回周数标准,所以:
weekofyear('2013-01-01') = weekofyear('2012-12-31') = 1
-- week starts on Monday, and 2012-12-31 is part of the first week of 2013
weekofyear('2012-01-01') = weekofyear('2011-12-31') = 52
-- last week of 2011 starts on 12-26, first week of 2012 starts on 01-02
weekofyear('2010-01-01') = weekofyear('2009-12-31') = 53
-- some years have 53 weeks
weekofyear('2007-01-01') != weekofyear('2006-12-31')
-- that's correct because the first day of 2007 was a Monday
由于您的要求更具体,如果您必须检查两天是否属于同一年的同一周,这仍然不足以回答您的问题。
与其使用week
, 或weekofyear
, 不如使用yearweek(date,mode)
函数 using mode=3
, 它返回与上述相同的周数, 但也可以在本周之前加上年份:
yearweek('2013-01-01', 3) = yearweek('2012-12-31', 3) = 201301
yearweek('2012-01-01', 3) = yearweek('2011-12-31', 3) = 201152
yearweek('2010-01-01', 3) = yearweek('2009-12-31', 3) = 200952
yearweek('2007-01-01', 3) != yearweek('2006-12-31', 3)
所以你的查询可能变成:
SELECT COUNT(*) AS `cnt`
FROM `orders`
WHERE YEARWEEK(`date_purchased`, 3) = YEARWEEK(DATE(), 3)