让我们首先创建一个表-
create table DemoTable621 (UserName varchar(100),UserEmailId varchar(100),UserLastPost datetime);
使用插入命令在表中插入一些记录-
insert into DemoTable621 values('John','John@gmail.com','2019-04-10 11:01:10');
insert into DemoTable621 values('John','John@gmail.com','2019-07-14 13:07:10');
使用select语句显示表中的所有记录-
select *from DemoTable621;
这将产生以下输出-
+----------+----------------+---------------------+
| UserName | UserEmailId | UserLastPost |
+----------+----------------+---------------------+
| John | John@gmail.com | 2019-04-10 11:01:10 |
| John | John@gmail.com | 2019-07-14 13:07:10 |
+----------+----------------+---------------------+
2 rows in set (0.00 sec)
以下是按列名分组的查询,并确保查询检索到最近的更新-
select UserName,UserEmailId,max(UserLastPost) from DemoTable621 group by UserName,UserEmailId;
这将产生以下输出-
+----------+----------------+---------------------+
| UserName | UserEmailId | max(UserLastPost) |
+----------+----------------+---------------------+
| John | John@gmail.com | 2019-07-14 13:07:10 |
+----------+----------------+---------------------+
1 row in set (0.19 sec)