如何使用group by返回最新值

时间:2011-04-28 14:12:25

标签: mysql

我有这个问题:

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分组时,我想要返回最近的datehistory}。

尝试GROUP BYORDER BY DESC,但不是最新的。我哪里错了?

2 个答案:

答案 0 :(得分:4)

假设idPRIMARY KEY上的history

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)上创建一个索引,以便快速工作。

答案 1 :(得分: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)应返回每个组的最长(或最近)日期。