使用DATE_FORMAT()并将说明符设置为仅显示MonthName和Year。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, AdmissionDate date );
使用插入命令在表中插入记录-
mysql> insert into DemoTable(AdmissionDate) values('2013-04-21'); mysql> insert into DemoTable(AdmissionDate) values('2014-01-31'); mysql> insert into DemoTable(AdmissionDate) values('2016-09-01'); mysql> insert into DemoTable(AdmissionDate) values('2018-12-12'); mysql> insert into DemoTable(AdmissionDate) values('2019-04-01');
使用选择命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+---------------+ | Id | AdmissionDate | +----+---------------+ | 1 | 2013-04-21 | | 2 | 2014-01-31 | | 3 | 2016-09-01 | | 4 | 2018-12-12 | | 5 | 2019-04-01 | +----+---------------+ 5 rows in set (0.00 sec)
这是在MySQL中格式化日期以返回MonthName和Year的查询-
mysql> select DATE_FORMAT(AdmissionDate,'%M %Y') AS MonthNameAndYear FROM DemoTable;
这将产生以下输出-
+------------------+ | MonthNameAndYear | +------------------+ | April 2013 | | January 2014 | | September 2016 | | December 2018 | | April 2019 | +------------------+ 5 rows in set (0.02 sec)