格式为 2015-07-01 11:15:30 的 MySQL 按月搜索结果?


为此请使用 MONTH() 和 YEAR()。我们首先创建一个表 -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ShippingDate datetime
   );
Query OK, 0 rows affected (0.54 sec)

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

mysql> insert into DemoTable(ShippingDate) values('2019-01-21 10:40:21');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(ShippingDate) values('2015-07-01 11:15:30');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(ShippingDate) values('2012-12-31 10:45:56');
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable;

将生成以下输出 -

+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
|  1 | 2019-01-21 10:40:21 |
|  2 | 2015-07-01 10:40:20 |
|  3 | 2012-12-31 10:45:56 |
+----+---------------------+
3 rows in set (0.00 sec)

以下是按 MONTH 和 YEAR 搜索结果的查询 -

mysql> select *from DemoTable where MONTH(ShippingDate)=7 and YEAR(ShippingDate)=2015;

将生成以下输出 -

+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
|  2 | 2015-07-01 11:15:30 |
+----+---------------------+
1 row in set (0.03 sec)

更新于: 2019-07-30

53 次浏览

启动您的 职业

完成该课程以获得认证

开始
广告