要在使用datetime时使用GROUP BY date,以下是语法-
select *from yourTableName GROUP BY date(yourColumnName);
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table groupByDateDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> UserName varchar(20), -> UserPostDatetime datetime -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Larry','2018-01-02 13:45:40'); mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Mike','2018-01-02 13:45:40'); mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Sam','2019-01-28 12:30:34'); mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('David','2019-02-10 11:35:54'); mysql> insert into groupByDateDemo(UserName,UserPostDatetime) values('Maxwell','2019-02-10 11:35:54');
使用select语句显示表中的所有记录。查询如下-
mysql> select *from groupByDateDemo;
这是输出-
+----+----------+---------------------+ | Id | UserName | UserPostDatetime | +----+----------+---------------------+ | 1 | Larry | 2018-01-02 13:45:40 | | 2 | Mike | 2018-01-02 13:45:40 | | 3 | Sam | 2019-01-28 12:30:34 | | 4 | David | 2019-02-10 11:35:54 | | 5 | Maxwell | 2019-02-10 11:35:54 | +----+----------+---------------------+ 5 rows in set (0.00 sec)
现在让我们在使用datetime时按日期分组。查询如下-
mysql> select *from groupByDateDemo GROUP BY date(UserPostDatetime);
以下是输出-
+----+----------+---------------------+ | Id | UserName | UserPostDatetime | +----+----------+---------------------+ | 1 | Larry | 2018-01-02 13:45:40 | | 3 | Sam | 2019-01-28 12:30:34 | | 4 | David | 2019-02-10 11:35:54 | +----+----------+---------------------+ 3 rows in set (0.00 sec)