如何在 MySQL 里从日期中选择月份和年份?
要选择 MySQL 中的月份和年份,可以使用 MONTH() 和 YEAR() 方法。我们首先创建一个表 -
mysql> create table DemoTable -> ( -> DueDate datetime -> ); Query OK, 0 rows affected (0.90 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable values('2019-01-21'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('2019-06-15'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2018-12-01'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2015-04-01'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('2016-08-14'); Query OK, 1 row affected (0.19 sec)
使用 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)
广告