我正在查询两个表(student2014和notes2014)中的数据,以便返回学生列表以及每个学生的笔记。为此,我使用以下select语句:
SELECT *
FROM students2014
LEFT JOIN notes2014
ON students2014.Student = notes2014.NoteStudent
WHERE students2014.Consultant='$Consultant'
ORDER BY students2014.LastName
这成功地给了我一个列表,但是有多个注释的学生出现两次,例如:
等...
我只想为每个学生出现最新的笔记,从而只提供一个每个学生的名单。
希望有道理吗?
答案 0 :(得分:1)
您需要使用子查询加入学生表。这样的事情应该有效:
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`
答案 1 :(得分:0)
尝试(我不测试它,但必须工作):
SELECT *, MAX(notes2014.notesID) as maxnoteid FROM students2014 LEFT JOIN notes2014 ON students2014.Student = notes2014.NoteStudent WHERE students2014.Consultant='$Consultant' AND notes2014.notesID = maxnoteid GROUP BY students2014.ID ORDER BY students2014.LastName
答案 2 :(得分:0)
select
*
from
`students2014`,
`notes2014`
where
`students2014`.`Student` = `notes2014`.`atudent`
and `notes2014`.`id` in (
select
'NoteStudent`,
max('NoteID`) as`MaxID`
from
`notes2014`
group by
`NoteStudent`
)`