这个问题已经有了答案:
Get top n records for each group of grouped results
10个答案
我正在查询两个表(students2014和notes2014)中的数据,以便返回学生列表以及每个学生的注释。为此,我使用以下select语句:

SELECT *
FROM students2014
LEFT JOIN notes2014
ON students2014.Student = notes2014.NoteStudent
WHERE students2014.Consultant='$Consultant'
ORDER BY students2014.LastName

这成功地给了我一个列表,但是有一个以上注释的学生出现两次,例如:
学生A-笔记
学生A-笔记
学生B-注
学生C-注
等。。。
我只希望为每个学生显示最新的便条,这样每个学生的列表只发送一次。
希望这有意义?

最佳答案

您需要用子查询连接studends表。这样的做法应该管用:

SELECT *
FROM `students2014`
LEFT JOIN (
    SELECT `note`, `NoteStudent`
    FROM `notes2014`
    HAVING `NoteID` = MAX(`NoteID`)
    GROUP BY `NoteStudent`
) `notes`
ON `students2014`.`Student` = `notes`.`NoteStudent`
WHERE `students2014`.`Consultant`='$Consultant'
ORDER BY `students2014`.`LastName`

10-08 00:14