This question already has an answer here:
I am querying data from two tables (students2014 and notes2014) in order to return a list of students along with notes on each student. To do this I am using the following select statement:
SELECT *
FROM students2014
LEFT JOIN notes2014
ON students2014.Student = notes2014.NoteStudent
WHERE students2014.Consultant='$Consultant'
ORDER BY students2014.LastName
This successfully gives me a list, however students with more than one note appear twice, for e.g:
etc...
I only want the latest note to appear for each student, thus delivering a list of each student only once.
Hope that makes sense?
</div>
You need to join the studends table with a sub query. Something like this should work:
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`
Try (I don't test it, but must work):
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
select
*
from
`students2014`,
`notes2014`
where
`students2014`.`Student` = `notes2014`.`atudent`
and `notes2014`.`id` in (
select
'NoteStudent`,
max('NoteID`) as`MaxID`
from
`notes2014`
group by
`NoteStudent`
)`