3

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:

  • Student a - Note
  • Student a - Note
  • Student b - Note
  • Student c - Note

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?

Phil Howell
  • 79
  • 2
  • 8

3 Answers3

1

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`
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
0

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
CreatoR
  • 1,654
  • 10
  • 14
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`
  )`
Andrew
  • 8,445
  • 3
  • 28
  • 46