MySQL 查询获取带年份和月份的日期?
mysqlmysqli database
要获取带年份和月份的日期,您可以使用 MySQL 中的 YEAR() 和 MONTH() 函数。让我们首先创建一个表 −
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ShippingDate datetime ); Query OK, 0 rows affected (0.48 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(ShippingDate) values('2019-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(ShippingDate) values('2018-12-01'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ShippingDate) values('2019-06-02'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable(ShippingDate) values('2019-11-18'); Query OK, 1 row affected (0.10 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 1 | 2019-01-31 00 :00 :00 | | 2 | 2018-12-01 00 :00 :00 | | 3 | 2019-06-02 00 :00 :00 | | 4 | 2019-11-18 00 :00 :00 | +----+-----------------------+ 4 rows in set (0.00 sec)
以下是根据特定年份和月份获取日期的查询 −
mysql> select *from DemoTable where ( year(ShippingDate)='2019') and (month(ShippingDate)='06');
输出
+----+-----------------------+ | Id | ShippingDate | +----+-----------------------+ | 3 | 2019-06-02 00 :00 :00 | +----+-----------------------+ 1 row in set (0.07 sec)