我有这个问题:
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 BY
和ORDER BY DESC
,但不是最新的。我哪里错了?
答案 0 :(得分:4)
假设id
是PRIMARY 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)
应返回每个组的最长(或最近)日期。