MySQL查询按年获取记录
要按年份获取记录,请使用YEAR()
MySQL中的方法-
select *from yourTableName where year(yourColumnName)=yourYearValue;
让我们首先创建一个表-
mysql> create table DemoTable -> ( -> CustomerName varchar(100), -> ShippingDate datetime -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('Chris','2019-01-21'); mysql> insert into DemoTable values('Robert','2018-02-21'); mysql> insert into DemoTable values('David','2016-04-01');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+--------------+---------------------+ | CustomerName | ShippingDate | +--------------+---------------------+ | Chris | 2019-01-21 00:00:00 | | Robert | 2018-02-21 00:00:00 | | David | 2016-04-01 00:00:00 | +--------------+---------------------+ 3 rows in set (0.00 sec)
以下是按年份获取记录的查询-
mysql> select *from DemoTable -> where year(ShippingDate)=2016;
输出结果
这将产生以下输出-
+--------------+---------------------+ | CustomerName | ShippingDate | +--------------+---------------------+ | David | 2016-04-01 00:00:00 | +--------------+---------------------+ 1 row in set (0.04 sec)