在 MySQL 中为星期几获取星期数?
MySQL DAYOFWEEK() 函数返回 1 表示星期日,2 表示星期一,以此类推,依次表示星期几。让我们先创建一个表,以了解示例 −
mysql> create table DayOfWeekDemo −> ( −> Issuedate datetime −> ); Query OK, 0 rows affected (0.52 sec)
在表中插入日期,使用 insert 命令。查询如下 −
mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 5 day)); Query OK, 1 row affected (0.52 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 6 day)); Query OK, 1 row affected (0.13 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 7 day)); Query OK, 1 row affected (0.10 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 8 day)); Query OK, 1 row affected (0.15 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 9 day)); Query OK, 1 row affected (0.10 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 10 day)); Query OK, 1 row affected (0.13 sec) mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 11 day)); Query OK, 1 row affected (0.10 sec)
然后,可以通过 select 语句显示表中存在多少条记录。查询如下 −
mysql> select *from DayOfWeekDemo;
以下是输出 −
+---------------------+ | Issuedate | +---------------------+ | 2018-12-03 00:00:00 | | 2018-12-04 00:00:00 | | 2018-12-05 00:00:00 | | 2018-12-06 00:00:00 | | 2018-12-07 00:00:00 | | 2018-12-08 00:00:00 | | 2018-12-09 00:00:00 | +---------------------+ 7 rows in set (0.00 sec)
查看上表:2018-12-03 是星期一,2018-12-04 是星期二,以此类推。以下是返回星期几索引的查询 −
mysql> select dayofweek(Issuedate) as WeekNumber from DayOfWeekDemo;
以下是输出显示的星期天数 −
+------------+ | WeekNumber | +------------+ | 2 | | 3 | | 4 | | 5 | | 6 | | 7 | | 1 | +------------+ 7 rows in set (0.00 sec)
广告