MySQL查询以选择特定月份的所有条目
要选择MySQL中特定月份的所有条目,请使用monthname()
或month()
函数。
语法如下。
select *from yourTableName where monthname(yourColumnName)='yourMonthName';
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table selectAllEntriesDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> ShippingDate datetime -> );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2019-01-21'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2018-02-24'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2010-10-22'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2011-04-12'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2013-02-10'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2014-02-15'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2016-06-14'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2017-02-14'); mysql> insert into selectAllEntriesDemo(ShippingDate) values('2015-03-29');
使用select语句显示表中的所有记录。
查询如下。
mysql> select *from selectAllEntriesDemo;
以下是输出。
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 1 | 2019-01-21 00:00:00 | | 2 | 2018-02-24 00:00:00 | | 3 | 2010-10-22 00:00:00 | | 4 | 2011-04-12 00:00:00 | | 5 | 2013-02-10 00:00:00 | | 6 | 2014-02-15 00:00:00 | | 7 | 2016-06-14 00:00:00 | | 8 | 2017-02-14 00:00:00 | | 9 | 2015-03-29 00:00:00 | +----+---------------------+ 9 rows in set (0.00 sec)
以下是查询以选择特定月份的所有条目:
mysql> select *from selectAllEntriesDemo where monthname(ShippingDate)='February';
这是输出。
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 2 | 2018-02-24 00:00:00 | | 5 | 2013-02-10 00:00:00 | | 6 | 2014-02-15 00:00:00 | | 8 | 2017-02-14 00:00:00 | +----+---------------------+ 4 rows in set (0.00 sec)
这是一个替代查询。
mysql> select *from selectAllEntriesDemo where month(ShippingDate)=2;
以下是输出。
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 2 | 2018-02-24 00:00:00 | | 5 | 2013-02-10 00:00:00 | | 6 | 2014-02-15 00:00:00 | | 8 | 2017-02-14 00:00:00 | +----+---------------------+ 4 rows in set (0.04 sec)