从日期格式中提取年月的方法?
要想从日期格式中提取年份,可以使用 MySQL 自带的 YEAR() 函数。 查询如下 −
mysql> SELECT YEAR(curdate()) as OnlyYearFromCurrentDate;
输出如下 −
+-------------------------+ | OnlyYearFromCurrentDate | +-------------------------+ | 2018 | +-------------------------+ 1 row in set (0.00 sec)
也可以用以下方式进行操作 −
mysql> SELECT YEAR(date(now())) as OnlyYearFromCurrentDate;
输出如下 −
+-------------------------+ | OnlyYearFromCurrentDate | +-------------------------+ | 2018 | +-------------------------+ 1 row in set (0.00 sec)
通过这种方式,即使列是 varchar 类型也能实现这个操作。我们先创建一个表 −
mysql> create table ExtractYearDemo −> ( −> YourDueTime varchar(200) −> ); Query OK, 0 rows affected (1.15 sec)
使用 insert 命令将记录插入表中。查询如下 −
mysql> insert into ExtractYearDemo values('27-10-2011'); Query OK, 1 row affected (0.16 sec) mysql> insert into ExtractYearDemo values('28-11-2012'); Query OK, 1 row affected (0.15 sec) mysql> insert into ExtractYearDemo values('29-12-2018'); Query OK, 1 row affected (0.14 sec) mysql> insert into ExtractYearDemo values('01-01-2019'); Query OK, 1 row affected (0.15 sec)
使用 SELECT 语句显示表中的所有记录。查询如下 −
mysql> select *from ExtractYearDemo;
输出如下 −
+-------------+ | YourDueTime | +-------------+ | 27-10-2011 | | 28-11-2012 | | 29-12-2018 | | 01-01-2019 | +-------------+ 4 rows in set (0.00 sec)
当列为 varchar 类型时,从表列中提取年份的查询如下 −
mysql> select YEAR(STR_TO_DATE(yourDueTime, "%d-%m-%Y")) As OnlyYearFromDate from ExtractYearDemo;
显示年份的输出如下 −
+------------------+ | OnlyYearFromDate | +------------------+ | 2011 | | 2012 | | 2018 | | 2019 | +------------------+ 4 rows in set (0.00 sec)
广告