如何按列名分組並確保查詢檢索到 MySQL 中的最後更新?


讓我們首先建立一個表 -

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)

更新於: 23-8-2019

75 次瀏覽

啟動您的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.