mysqlsqljoin

query with JOIN and LEFT JOIN


Students

student_id student_name
1 Alice
2 Bob
13 John
6 Alex

Subjects

subject_name
Math
Physics
Programming

Examinations

student_id subject_name
1 Math
1 Physics
1 Programming
2 Programming
1 Physics
1 Math
13 Math
13 Programming
13 Physics
2 Math
1 Math
SELECT s.student_id,s.student_name,b.subject_name,
    COUNT(e.subject_name) as attended_exams
FROM Students as s
INNER JOIN Subjects as b
LEFT JOIN Examinations as e
ON s.student_id=e.student_id
AND b.subject_name=e.subject_name
GROUP BY s.student_id,b.subject_name;

What is the role of the INNER JOIN, given Students and Subjects have no intersection or common columns?

How do I understand/imagine a table right before the LEFT JOIN was executed?

How do I decide whether to include Subject, given we have all the subjects in Examinations already?

This is a problem from LeetCode:
https://leetcode.com/problems/students-and-examinations/


Solution

  • You query is equivalent to:

    SELECT s.student_id, s.student_name, b.subject_name, 
           COUNT(e.subject_name) as attended_exams
    FROM Students s CROSS JOIN
         Subjects b LEFT JOIN
         Examinations as e
         ON s.student_id = e.student_id AND 
            b.subject_name = e.subject_name
    GROUP BY s.student_id, b.subject_name;
    

    MySQL extends the JOIN syntax so the ON clause is optional. Personally, I think this is a very bad idea. A CROSS JOIN is a CROSS JOIN and should be specified as such.

    What the query is doing is generating a row for every student/subject combination. It is then counting how many examinations each student has attended in each subject.