2010-01-17 102 views
1

我有一個表在MySQL:Mysql的GROUP BY和獨特的價值

 
SID DID MessageType DateOf Message 
1 255 LOG  2010-01-17 15:02:05 Log msg 1  
2 255 USER 2010-01-17 19:02:05 User msg 1 
3 211 LOG  2010-01-17 15:06:55 Log msg 2  
4 211 ADMIN 2010-01-17 22:06:55 Admin msg 1 

我需要得到最後(通過DateOf)消息和消息類型,細分電子郵件由DID, 下令DateOf DESC

權結果將是:

 
DID MessageType DateOf Message 
211 ADMIN  2010-01-17 22:06:55 Admin msg 1 
255 USER  2010-01-17 19:02:05 User msg 1 

我該如何做這個select查詢? MySQL 5.1

回答

1
SELECT * FROM `test` WHERE (DID,DateOf) IN (
    SELECT DID,MAX(DateOf) FROM `test` GROUP BY DID 
) GROUP BY DID ORDER BY DateOf DESC 

子查詢爲每個DID選擇max DateOf。 外部查詢選擇具有這些DateOf和DID的行。 GROUP BY在外部查詢中確保每個DID的結果中只有一行(如果表中有多個具有相同DID和DateOf的行,則它將返回其中一個,而沒有任何特定順序)。

0
SELECT * FROM test t JOIN (
    SELECT DID, MAX(DateOf) AS DateOf FROM test GROUP BY DID 
) t2 ON (t.DID = t2.DID AND t.DateOf = t2.DateOf) 
ORDER BY t.DateOf DESC; 

另一種解決方案:

SELECT * FROM test t WHERE DateOf = (
    SELECT MAX(DateOf) FROM test t2 WHERE t2.DID = t.DID 
) ORDER BY DateOf DESC; 

當我解決這個前一段時間我用Google搜索這個有用的文章:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/