Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join three tables with MAX function

Tags:

sql

mysql

I have three tables: student, subject and score.
I want to display the details of max(subject_id) of each student.

student table

student_id   student_name  exam_date
   1            Sharukh     24/06/12
   2            Amir        23/06/12

subject table

subject_id    sub_name
   200         Maths
   300         English
   400         Science

score table

student_id   subject_id     score
    1           200         50 
    1           300         20
    2           300         10

The result should be:

student_id    student_name     subject_id      score
     1          Sharukh           300            20
     2          Amir              300            10
like image 717
user2431727 Avatar asked Jun 22 '16 09:06

user2431727


2 Answers

Use the MAX function and GROUP BY your other selections.

SELECT st.student_id, st.student_name, MAX(su.subject_id) AS subject_id, sc.score
FROM student st
INNER JOIN score sc ON st.student_id = sc.student_id
INNER JOIN subject su ON sc.subject_id = su.subject_id
WHERE su.subject_id = (SELECT MAX(sca.subject_id) 
                       FROM score sca 
                       WHERE sc.student_id = sca.student_id 
                       GROUP BY sca.student_id)
GROUP BY st.student_id, st.student_name, sc.score

Output:

student_id  student_name  subject_id  score
1           Sharukh       300         20
2           Amir          300         10

SQL Fiddle: http://sqlfiddle.com/#!9/71c46a/7/0

Without the GROUP BY

SELECT st.student_id, st.student_name, su.subject_id, sc.score
FROM student st
INNER JOIN score sc ON st.student_id = sc.student_id
INNER JOIN subject su ON sc.subject_id = su.subject_id
WHERE su.subject_id = (SELECT MAX(sca.subject_id) 
                       FROM score sca 
                       WHERE sc.student_id = sca.student_id 
                       GROUP BY sca.student_id)
like image 60
Matt Avatar answered Sep 21 '22 00:09

Matt


Try this;)

select t1.student_id, t1.student_name, t3.subject_id, t3.score
from student t1
inner join subject t2
inner join score t3
inner join (
    select max(subject_id) as subject_id, student_id
    from score group by student_id
) t4 on t3.student_id = t4.student_id and t3.subject_id = t4.subject_id
and t2.subject_id = t3.subject_id 
and t1.student_id = t3.student_id

SQLFiddle DEMO HERE

like image 33
Blank Avatar answered Sep 20 '22 00:09

Blank