您可以借助MONTH()
方法选择特定月份。语法如下-
SELECT yourColumnName FROM yourTableName WHERE MONTH(yourColumnName) = yourValue;
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table UserLoginTimeInformation -> ( -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserLoginDatetime datetime -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values(date_add(now(), interval 3 month)); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-05-13 13:45:34'); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2013-06-11 12:41:04'); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2012-05-25 15:03:24'); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2017-05-21 12:12:40'); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2018-09-29 11:30:34'); mysql> insert into UserLoginTimeInformation(UserLoginDatetime) values('2016-03-10 16:40:45');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from UserLoginTimeInformation;
以下是输出-
+--------+---------------------+ | UserId | UserLoginDatetime | +--------+---------------------+ | 1 | 2019-05-13 15:01:24 | | 2 | 2013-05-13 13:45:34 | | 3 | 2013-06-11 12:41:04 | | 4 | 2012-05-25 15:03:24 | | 5 | 2017-05-21 12:12:40 | | 6 | 2018-09-29 11:30:34 | | 7 | 2016-03-10 16:40:45 | +--------+---------------------+ 7 rows in set (0.00 sec)
这是查询,根据月份号从表中选择所有记录-
mysql> select UserLoginDatetime from UserLoginTimeInformation where MONTH(UserLoginDatetime) = 5;
输出结果
+---------------------+ | UserLoginDatetime | +---------------------+ | 2019-05-13 15:01:24 | | 2013-05-13 13:45:34 | | 2012-05-25 15:03:24 | | 2017-05-21 12:12:40 | +---------------------+ 4 rows in set (0.00 sec)