如何按列名分组并确保查询检索 MySQL 中的最新更新?
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable621 (UserName varchar(100),UserEmailId varchar(100),UserLastPost datetime); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable621 values('John','John@gmail.com','2019-04-10 11:01:10'); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable621 values('John','John@gmail.com','2019-07-14 13:07:10'); Query OK, 1 row affected (0.15 sec)
使用 select 语句显示表中的所有记录 −
mysql> 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)
以下是按列名分组的查询,并确保查询检索最新的更新 −
mysql> 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)