问题
I'm using
WHERE WEEK(curdate,3)-WEEK(date)=1
to get all lines of a table that are recorded on the last working week (Monday to Sunday). Works well the whole year, but in January that will return 0 for some time, so I have to take
WHERE WEEK(curdate,3)+53-WEEK(date)
in that case. I can't use OR
because it would take both current year info and last year info when both exist. I already tried COALESCE
and IFNULL
methods:
WHERE COALESCE(
(WEEK(curdate(),3)-WEEK(date,3) = 1),
(WEEK(curdate(),3)+53-WEEK(date,3) = 1
)
It works well for the whole year but doesn't manage the case when IFNULL
is true.
Please give me advice on effective handling of this case.
回答1:
You can get the date of the Monday of the current week using:
select SUBDATE(curdate(), WEEKDAY(curdate()));
and then use the date of the Monday of this week and the Monday of the previous week in your predicate:
WHERE date >= SUBDATE(curdate(), WEEKDAY(curdate())) - interval 1 week
AND date < SUBDATE(curdate(), WEEKDAY(curdate()))
来源:https://stackoverflow.com/questions/15154655/mysql-getting-records-over-the-last-working-week