-1

What happens actually when we use cascaded join statements

select student.name, count(teacher.id)
from student
left join course on student.course_id = course.id
left join teacher on student.teacher_id = teacher.id
group by student.name;

It seems when I used only the first left join alone it returned 30 rows while using the second left join alone returned 20 rows. But using together returns 600 rows. What is actually happening ? Does the result from the first left join is used in the second ? I don't understand the semantics. Help me understand it.

Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66

2 Answers2

4

Since you don't have any join conditions between teacher and course, you're getting a full cross-product between each of the other two joins. Since one join returns 20 rows and the other returns 30 rows, the 3-way join returns 20x30 = 600 rows. Its equivalent to:

SELECT t1.name, count(t2.id)
FROM (SELECT student.name
      FROM student
      LEFT JOIN course ON student.id = course.id) AS t1
CROSS JOIN
     (SELECT teacher.id
      FROM student
      LEFT JOIN teacher ON student.id = teacher.id) AS t2
GROUP BY t1.name

Notice that the CROSS JOIN of the two subqueries has no ON condition.

The correct way to structure this database is as follows:

  • student table: id (PK), name
  • course table: id (PK), name, fee, credits
  • student_course table: id (PK), student_id (FK), course_id (FK), unique key on (student_id, course_id)

Then to get the name of each student and the average course fee, you would do:

SELECT s.name, AVG(c.fee) AS avg_fee
FROM student AS s
LEFT JOIN student_course AS sc ON s.id = sc.student_id
LEFT JOIN course AS c ON sc.course_id = c.id
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

All Mysql joins are graphically explained here. Take a look and choose correct joins for both joined tables.

Community
  • 1
  • 1
LHristov
  • 1,103
  • 7
  • 16