Mysql GROUP BY和唯一值

时间:2010-01-17 13:22:48

标签: mysql group-by grouping

我在MySQL中有一个表:

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)Message和MessageType,由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

我该怎么做这个选择查询? MySQL 5.1

2 个答案:

答案 0 :(得分: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选择最大DateOf。 外部查询选择具有DateOf和DID的行。 外部查询中的GROUP BY确保每个DID的结果中只有一行(如果表中有多个具有相同DID和DateOf的行,则返回其中一行而没有任何特定顺序)。

答案 1 :(得分: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;

前一段时间我解决这个问题后,我搜索了这篇有用的文章:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/