Evemtor Evemtor - 4 months ago 12
MySQL Question

Error on Left Join three tables in mysql

I set all the day reading Questions on stackoverflow of how to jouin 3 table in one SQL query , I try it many times but it did not work !!

my case are like this , I want to understand how it is work and how should I do it.

my SQL query is the following :

SELECT students.id,
students.name,
students.age,
students.subjects,
students.teacher from students
LEFT JOIN subjects ON students.subjects = subjects.subject_id
LEFT JOIN teachers ON students.teacher = teachers.teacher_id


What is the wrong in my case ?

Answer

You are missing a condition in the second LEFT JOIN:

SELECT s.id, s.name, s.age, s.subjects, s.teacher 
FROM students s LEFT JOIN
     subjects su
     ON s.subjects = su.subject_id LEFT JOIN
     teachers t
     ON s.teacher = t.teacher;

You should note, though, that the query is only fetching columns from students, so you don't need the joins (at this point, I'm guessing the query you want is more complicated).