从基于特定月份的MySQL表中选择数据?
使用MONTH()
MySQL中的方法选择基于月份的日期。让我们首先创建一个表-
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(10), -> UserPostMessageDate datetime, -> UserLikes int -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes) values('John','2019-01-31',4560); mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes) values('Sam','2019-06-28',790); mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes) values('Carol','2019-05-01',230); mysql> insert into DemoTable(UserName,UserPostMessageDate,UserLikes) values('David','2019-03-05',10000000);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
输出结果
这将产生以下输出-
+----+----------+---------------------+-----------+ | Id | UserName | UserPostMessageDate | UserLikes | +----+----------+---------------------+-----------+ | 1 | John | 2019-01-31 00:00:00 | 4560 | | 2 | Sam | 2019-06-28 00:00:00 | 790 | | 3 | Carol | 2019-05-01 00:00:00 | 230 | | 4 | David | 2019-03-05 00:00:00 | 10000000 | +----+----------+---------------------+-----------+ 4 rows in set (0.00 sec)
以下是根据特定月份从表中选择数据的查询-
mysql> select Id,UserName,UserLikes from DemoTable where MONTH(UserPostMessageDate)=6;
输出结果
这将产生以下输出-
+----+----------+-----------+ | Id | UserName | UserLikes | +----+----------+-----------+ | 2 | Sam | 790 | +----+----------+-----------+ 1 row in set (0.00 sec)