Search code examples
mysqlleft-join

LEFT JOIN on Max Value


Suppose I have the following two tables:

STUDENT
studentid   lastname   firstname
1           Smith      John
2           Drew       Nancy

STUDENT_STORY
studentid   dateline   storyid   status
1           1328313600 10        2
1           1328313601 9         1
2           1328313602 14        2
2           1328313603 12        1

Now, I need an SQL query that would select each student along with the latest story for that student in the student story table.

I am trying this:

SELECT s.*, ss.*
FROM student AS s
LEFT JOIN (
    SELECT *
    FROM student_story
    WHERE student_story.studentid = s.studentid
    ORDER BY dateline DESC LIMIT 1
) AS ss ON (ss.studentid = s.studentid)

However, this query does not work. It complains about s.studentid being an unknown field in the where clause of the sub query.

Please suggest how I can achieve what I'm trying to do.

Thanks.


Solution

  • Try something like this:

    SELECT
      s.*,
      ss.*
    FROM
      student AS s
    LEFT JOIN
      student_story AS ss
    ON (ss.studentid = s.studentid)
    WHERE ss.dateline = (
      SELECT
        MAX(dateline)
      FROM
        student_story AS ss2
      WHERE
        ss2.studentid = s.studentid
    )