获取MySQL的星期几?

MySQLDAYOFWEEK()函数在星期日返回1,在星期一返回2,以此类推。让我们通过首先创建表来查看示例-

mysql> create table DayOfWeekDemo
−> (
   −> Issuedate datetime
−> );

借助insert命令将日期插入表中。查询如下-

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 5 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 6 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 7 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 8 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 9 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 10 day));

mysql> insert into DayOfWeekDemo values(date_add(curdate(),interval 11 day));

现在,您可以借助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)