2016-03-05 33 views
2

我使用MySQL。按順序通過MAX()

我想要的結果,是具有最高「時間」顯示行,其中「RES」 =「漢斯」和基團「FRM」。

我想擺弄GROUP BY,ORDER BY,MAX(時間) - 我要去任何地方。

我的表: '消息'

| frm | res | time | msg | opnd | 
| poul | hans | 0916 | hi there | 1 | 
| john | hans | 1033 | waz up | 1 | 
| hans | john | 1140 | new text | 0 | 
| poul | john | 1219 | message | 0 | 
| poul | hans | 1405 | respond | 0 | 
| john | hans | 1544 | write | 0 | 

結果我想:

poul - hans - 1405 - respond - 0 
john - hans - 1544 - write - 0 

結果我得到:

poul - hans - 1405 - hi there - 1 
john - hans - 1544 - waz up - 1 

我得到了正確的 '時間'但錯誤的「味精」和「不正確」。

我的代碼:

SELECT frm, res, MAX(time), msg, opnd 
FROM messages 
WHERE res = 'hans' 
GROUP BY frm 
ORDER BY time DESC 

回答

2

有幾個方法可以做到這一點。一種是使用子查詢和join回原始表:

SELECT m.* 
FROM messages m 
    JOIN (
     SELECT frm, res, MAX(time) maxtime 
     FROM messages 
     WHERE res = 'hans' 
     GROUP BY frm, res) m2 on m.frm = m2.frm 
         and m.res = m2.res 
         and m.time = m2.maxtime 
ORDER BY m.time DESC 

Mysql可以讓你忽略來自未在聚集中使用的group by條款場(錯誤IMO - 大多數其他數據庫不允許此行爲)。通過允許它,它只是返回一個隨機結果,儘管這是你正在經歷的。


Here'a使用outer join另一種方法,但我覺得以前更容易理解:

select m.* 
from messages m 
    left join messages m2 on m.frm = m2.frm 
         and m.res = m2.res 
         and m2.time > m.time 
where m2.frm is null 
    and m.res = 'hans' 
order by m.time desc 
+0

日Thnx,這似乎是工作。從來沒有想過這將是複雜的。 – CitronAutobot

0

您的問題是,你是通過分組一列,但您選擇了幾列。因此,對於其他非按列分組,您只能得到其中一個結果,而不是屬於最大(時間)值的結果。

你需要的東西,如:

select a.frm, a.res, b.max_time, a.msg, a.opnd from 
messages as a inner join 
(SELECT frm, MAX(time) as max_time 
FROM messages 
WHERE res = 'hans' 
GROUP BY frm) on a.frm = b.frm and a.time = b.max_time 
ORDER BY time DESC