我正在尝试编写一个查询,从一系列值中提取“最佳”记录:
SELECT s.swimmerName, r.resultTimeText, r.resultAgeGroup, r.resultEventID, v.venueName
FROM tblResults r
JOIN tblEvents e ON e.eventID = r.resultEventID
JOIN tblSwimmers s ON r.resultSwimmerID = s.swimmerID
JOIN tblVenues v ON e.resultVenueID = v.venueID
WHERE s.swimmerGender = %s
AND r.resultStroke = %s
GROUP BY s.swimmerName
这会选择我的所有记录,但人们会在不同时间列出两次(我知道DISTINCT的结果)。为每个人选择最佳时间的最佳方式是什么?
答案 0 :(得分:0)
您可以使用mysql的古怪分组来帮助您:
SELECT * FROM (
SELECT s.swimmerName, r.resultTimeText, r.resultAgeGroup, r.resultEventID, v.venueName
FROM tblResults r
JOIN tblEvents e ON e.eventID = r.resultEventID
JOIN tblSwimmers s ON r.resultSwimmerID = s.swimmerID
JOIN tblVenues v ON e.resultVenueID = v.venueID
WHERE s.swimmerGender = %s
AND r.resultStroke = %s
ORDER BY 2) x
GROUP BY swimmerName
ORDER BY 2
首先将数据排序为最快到最慢,然后按名称分组。在myswl(仅)中,并非所有非聚合列的分组都只会过滤为按列分组的每个唯一组合所遇到的第一个行。