如何在 MySQL 中选择落在特定星期几的行?


对于特定星期几,使用 DAYOFWEEK()。

我们先来创建一个表 -

mysql> create table DemoTable785 (
   CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   CustomerName varchar(100),
   ShoppingDate date
);
Query OK, 0 rows affected (0.61 sec)

使用 insert 命令向表中插入一些记录 -

mysql> insert into DemoTable785(CustomerName,ShoppingDate) values('Chris','2019-07-03');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable785(CustomerName,ShoppingDate) values('Robert','2019-07-01');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable785(CustomerName,ShoppingDate) values('David','2019-07-06');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable785(CustomerName,ShoppingDate) values('Carol','2019-07-19');
Query OK, 1 row affected (0.19 sec)

使用 select 语句显示表中的所有记录 -

mysql> select *from DemoTable785;

这会生成以下输出 -

+------------+--------------+--------------+
| CustomerId | CustomerName | ShoppingDate |
+------------+--------------+--------------+
| 1          | Chris        | 2019-07-03   |
| 2          | Robert       | 2019-07-01   |
| 3          | David        | 2019-07-06   |
| 4          | Carol        | 2019-07-19   |
+------------+--------------+--------------+
4 rows in set (0.00 sec)

以下是查询落在特定星期几的行 -

mysql> select *from DemoTable785 where DAYOFWEEK(ShoppingDate)=2;

这会生成以下输出 -

+------------+--------------+--------------+
| CustomerId | CustomerName | ShoppingDate |
+------------+--------------+--------------+
| 2          | Robert       | 2019-07-01   |
+------------+--------------+--------------+
1 row in set (0.00 sec)

更新于:09-9-2019

142 次浏览

开启您的 事业

通过完成课程获得认证

开始
广告