要在MySQL中选择月份和年份,可以使用MONTH()
和YEAR()
方法。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> DueDate datetime -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('2019-01-21'); mysql> insert into DemoTable values('2019-06-15'); mysql> insert into DemoTable values('2018-12-01'); mysql> insert into DemoTable values('2015-04-01'); mysql> insert into DemoTable values('2016-08-14');
使用select语句显示表中的所有记录-
mysql− select *from DemoTable;
输出结果
这将产生以下输出-
+---------------------+ | DueDate | +---------------------+ | 2019-01-21 00:00:00 | | 2019-06-15 00:00:00 | | 2018-12-01 00:00:00 | | 2015-04-01 00:00:00 | | 2016-08-14 00:00:00 | +---------------------+ 5 rows in set (0.00 sec)
以下是从MySQL选择月份和年份的查询-
mysql> select MONTH(DueDate) AS MONTH, YEAR(DueDate) AS YEAR from DemoTable;
输出结果
这将产生以下输出-
+-------+------+ | MONTH | YEAR | +-------+------+ | 1 | 2019 | | 6 | 2019 | | 12 | 2018 | | 4 | 2015 | | 8 | 2016 | +-------+------+ 5 rows in set (0.00 sec)