檢索每一個組中的最後一條記錄-MySQL - Retrieving the last record in each group - MySQL

問題:

There is a table messages that contains data as shown below: 有一個表messages ,其中包含數據,以下所示: this

Id   Name   Other_Columns
-------------------------
1    A       A_data_1
2    A       A_data_2
3    A       A_data_3
4    B       B_data_1
5    B       B_data_2
6    C       C_data_1

If I run a query select * from messages group by name , I will get the result as: 若是運行查詢,請select * from messages group by name ,結果將是: spa

1    A       A_data_1
4    B       B_data_1
6    C       C_data_1

What query will return the following result? 什麼查詢將返回如下結果? .net

3    A       A_data_3
5    B       B_data_2
6    C       C_data_1

That is, the last record in each group should be returned. 即,應返回每一個組中的最後一條記錄。 code

At present, this is the query that I use: 目前,這是我使用的查詢: ci

SELECT
  *
FROM (SELECT
  *
FROM messages
ORDER BY id DESC) AS x
GROUP BY name

But this looks highly inefficient. 但這看起來效率很低。 Any other ways to achieve the same result? 還有其餘方法能夠達到相同的結果嗎? get


解決方案:

參考一: https://stackoom.com/question/5VbM/檢索每一個組中的最後一條記錄-MySQL
參考二: https://oldbug.net/q/5VbM/Retrieving-the-last-record-in-each-group-MySQL
相關文章
相關標籤/搜索