2011-04-28 59 views
3

與組返回最近的值我有此查詢:如何通過

SELECT history.trackid, tracklist.artist, tracklist.event, tracklist.data, history.date 
FROM history JOIN tracklist ON history.trackid=tracklist.trackid 
GROUP BY trackid 
ORDER BY history.date DESC 

但我想最近trackid(由date)將返回當我history組。

試過GROUP BYORDER BY DESC,但不是最新的。我錯在哪裏?

回答

4

它最近沒有排序的原因是因爲GROUP BY創建了一個聚合結果。你可以嘗試:

SELECT h.trackid, t.artist, t.event, t.data 
FROM  history AS h 
    JOIN tracklist AS t 
    ON h.trackid = t.trackid 
GROUP BY h.trackid 
ORDER BY MAX(h.date) DESC 

因爲您已經聚集效果,MAX(history.date)應返回的最大(或最近的)日期爲每個組。

4

假設idPRIMARY KEYhistory

SELECT t.trackid, t.artist, t.event, t.data, h.date 
FROM tracklist t 
LEFT JOIN 
     history h 
ON  h.id = 
     (
     SELECT hi.id 
     FROM history 
     WHERE hi.trackid = t.trackid 
     ORDER BY 
       hi.trackid DESC, hi.date DESC, hi.id DESC 
     LIMIT 1 
     ) 

history (trackid, date, id)此創建的索引快速地工作。