I need to fetch all records from current week. But since Monday Dec 31st was in 2012, mysql treats it as week 53, instead of week 1 of 2013. How can I get around that?
Query:
SELECT COUNT(*) AS `cnt`
FROM `orders`
WHERE WEEK(`date_purchased`, 1) = WEEK(NOW(), 1)
AND (
(
MONTH(`date_purchased`) = MONTH(NOW() - INTERVAL 1 WEEK)
AND YEAR(`date_purchased`) = YEAR(NOW() - INTERVAL 1 WEEK)
)
OR (
MONTH(`date_purchased`) = MONTH(NOW())
AND YEAR(`date_purchased`) = YEAR(NOW())
)
)
According to ISO standard, week number 1 of the year is the first week with the majority of its days in the starting year, and while
week(date,1)returns week 53 for ‘2012-12-31’,week(date,3)or its equivalentweekofyear(date)correctly return week number according to this standard, so:Since your request is more specific, if you have to check if two days are part of the same week of the same year, this is still not enough to answer your question.
Instead of using
week, orweekofyear, it’s better to useyearweek(date,mode)function, usingmode=3, that returns the same week numbers as above, but also preceded by the year this week refers to:so your query could become: