Benjamin Crouzier
Benjamin Crouzier

Reputation: 41895

Mysql inner join with condition on joined data

I have the folowing tables:

Table student:

id  name
1   foo
2   bar
3   baz

Table mark

student_id  mark  date
1           9     2011-08-10
1           20    2011-08-09
1           5     2011-08-08
2           12    2011-08-09
2           8     2011-08-10
3           10    2011-08-10

I want each student with their last mark, ie

foo 9
bar 8
baz 10

How can i do that with mysql?

EDIT: The point of this example is how to add a sorting condiction on the joined table.

Upvotes: 1

Views: 341

Answers (1)

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58441

You would use a GROUP BYand the MAXaggregate function to create a recordset containing all students with their latest date. This recordset can then be joined back to the original tables to retrieve the other columns needed.

The GROUP BY Statement

The GROUP BY statement is used in conjunction with the aggregate functions to group the result-set by one or more columns.

MAX([DISTINCT] expr)

Returns the maximum value of expr. MAX() may take a string argument; in such cases, it returns the maximum string value.

SQL Statement

SELECT  s.name
        , m.Mark
FROM    student s
        INNER JOIN mark m ON m.student_id = s.id
        INNER JOIN (
          SELECT  s.id,
                  MAX(m.Date) as MaxDate
          FROM    student s
                  INNER JOIN mark m ON m.student_id = s.id
          GROUP BY
                  s.id
        ) sm ON sm.id = m.student_id AND sm.MaxDate = m.date

Upvotes: 4

Related Questions