可以通过以下三种方式在MySQL中完成
EXTRACT()
方法为了共同提取YEAR和MONTH,我们可以使用EXTRACT函数。我们需要提供YEAR_MONTH作为此函数的参数。要理解它,请考虑使用表'Collegedetail'中的数据的以下功能-
mysql> Select EXTRACT(YEAR_MONTH From estb) from collegedetail; +-------------------------------+ | EXTRACT(YEAR_MONTH From estb) | +-------------------------------+ | 201005 | | 199510 | | 199409 | | 200107 | | 201007 | +-------------------------------+ 5 rows in set (0.00 sec)
它既可以汇总也可以分别提取年和月。顾名思义,我们还可以格式化其输出。要理解它,请请看以下示例,该示例使用表'Collegedetail'中的数据-
mysql> Select DATE_FORMAT(estb, '%Y %m') from collegedetail; +----------------------------+ | DATE_FORMAT(estb, '%Y %m') | +----------------------------+ | 2010 05 | | 1995 10 | | 1994 09 | | 2001 07 | | 2010 07 | +----------------------------+ 5 rows in set (0.00 sec) mysql> Select DATE_FORMAT(estb, '%Y') from Collegedetail; +-------------------------+ | DATE_FORMAT(estb, '%Y') | +-------------------------+ | 2010 | | 1995 | | 1994 | | 2001 | | 2010 | +-------------------------+ 5 rows in set (0.00 sec) mysql> Select DATE_FORMAT(estb, '%m') from Collegedetail; +-------------------------+ | DATE_FORMAT(estb, '%m') | +-------------------------+ | 05 | | 10 | | 09 | | 07 | | 07 | +-------------------------+ 5 rows in set (0.00 sec) mysql> Select DATE_FORMAT(estb, '%M') from Collegedetail; +-------------------------+ | DATE_FORMAT(estb, '%M') | +-------------------------+ | May | | October | | September | | July | | July | +-------------------------+ 5 rows in set (0.10 sec)
YEAR()
以及MONTH()
它将使用两个不同的函数分别提取年和月。要理解它,请请看以下示例,该示例使用表'Collegedetail'中的数据-
mysql> Select YEAR(estb) AS 'Year', MONTH(estb) As 'MONTH' From collegedetail; +------+-------+ | Year | MONTH | +------+-------+ | 2010 | 5 | | 1995 | 10 | | 1994 | 9 | | 2001 | 7 | | 2010 | 7 | +------+-------+ 5 rows in set (0.00 sec)