Computer >> Máy Tính >  >> Lập trình >> MySQL

Làm thế nào để nhóm theo tên cột và đảm bảo truy vấn truy xuất bản cập nhật cuối cùng trong MySQL?


Trước tiên, chúng ta hãy tạo một bảng -

mysql> create table DemoTable621 (UserName varchar(100),UserEmailId varchar(100),UserLastPost datetime);
Query OK, 0 rows affected (0.59 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

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)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable621;

Điều này sẽ tạo ra kết quả sau -

+----------+----------------+---------------------+
| 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)

Sau đây là truy vấn để nhóm theo tên cột và đảm bảo truy vấn truy xuất bản cập nhật cuối cùng -

mysql> select UserName,UserEmailId,max(UserLastPost) from DemoTable621 group by UserName,UserEmailId;

Điều này sẽ tạo ra kết quả sau -

+----------+----------------+---------------------+
| UserName | UserEmailId    | max(UserLastPost)   |
+----------+----------------+---------------------+
| John     | John@gmail.com | 2019-07-14 13:07:10 |
+----------+----------------+---------------------+
1 row in set (0.19 sec)