1.WEEK(date, mode);
WEEK函数接受两个参数:
- date是要获取周数的日期。
- mode是一个可选参数,用于确定周数计算的逻辑。它允许您指定本周是从星期一还是星期日开始,返回的周数应在0到52之间或0到53之间。
如果忽略mode参数,默认情况下WEEK函数将使用default_week_format系统变量的值。
要获取default_week_format变量的当前值,请使用SHOW VARIABLES语句如下:
mysql> SHOW VARIABLES LIKE 'default_week_format';
+---------------------+-------+
| Variable_name | Value |
+---------------------+-------+
| default_week_format | 0 |
+---------------------+-------+
1 row in set
在我们的服务器中,default_week_format的默认值为0,下表格说明了mode参数如何影响WEEK函数:
模式 | 一周的第一天 | 范围 |
0 | 星期日 | 0-53 |
1 | 星期一 | 0-53 |
2 | 星期日 | 1-53 |
3 | 星期一 | 1-53 |
4 | 星期日 | 0-53 |
5 | 星期一 | 0-53 |
6 | 星期日 | 1-53 |
7 | 星期一 | 1-53 |
上表中“今年有4天以上”表示:
- 如果星期包含1月1日,并且在新的一年中有4天或更多天,那么这周是今年的第1周。
- 否则,这一周的数字是前一年的最后一周,下周才是今年的第1周。
所以在需要考虑年份的时候,使用YEARWEEK函数更加恰当。
2.MySQL 的 YEARWEEK 是获取年份和周数的一个函数,函数形式为 YEARWEEK(
date
[,mode
])
例如 2010-3-14 ,礼拜天
SELECT YEARWEEK('2010-3-14') 返回 11
SELECT YEARWEEK('2010-3-14',1) 返回 10
其中第二个参数是 mode ,具体指的意思如下:
Mode | First day of week | Range | Week 1 is the first week … |
0 | Sunday | 0-53 | with a Sunday in this year |
1 | Monday | 0-53 | with more than 3 days this year |
2 | Sunday | 1-53 | with a Sunday in this year |
3 | Monday | 1-53 | with more than 3 days this year |
4 | Sunday | 0-53 | with more than 3 days this year |
5 | Monday | 0-53 | with a Monday in this year |
6 | Sunday | 1-53 | with more than 3 days this year |
7 | Monday | 1-53 | with a Monday in this year |
3. WORKOFYEAR(date)函数是计算出当前日期所在周数,和YEARWEEK('日期',1)的周数一致,但YEARWEEK('日期',1)在小于10的时候,不带0
SELECT weekofyear('2020-8-17'); # 34
SELECT weekofyear('2020-8-16'); # 33