简体   繁体   中英

using left join on mutiple tables with conditional statement

I have a problem with MYSQL which can only be solved by using inner join which i am not so good with, i have four tables.

Table 1: classrooms classroomID, name, .......

Table 2: teachers fname, mname, lname, .......

Table 3: subjects subjectID, name, classroom_id, .....

table 4 Teachers_subjects teacher_id and subject_id

i want a query to get me all class names (classrooms.name) and all its subjects name (subjects.name) where subjects.classroom_id = classrooms.classroomID

I also want to get the names of the teachers (teachers.name) where Teachers_subjects.subject_id = subjects.subjectID and Teachers_subjects.teacher_id= teachers.teacherID.

i am currently using this query :

SELECT classrooms.name, subjects.name, 
concat(teachers.fname,' ',teachers.mname,' ',teachers.lname) as Teachers_name  
FROM classrooms, subjects, teachers, teachers_subjects 
WHERE
subjects.classroom_id=classrooms.classroomID 
AND 
teachers_subjects.teacher_id=teachers.teacherID 
AND
teachers_subjects.subject_id=subjects.subjectID

I get what i want but i want to get all classes and their corresponding subjects even if its not on the table teachers_subjects. this is to list all classes and its subjects even if the subject is not assigned to any teacher.

Thanks

You could try something like

SELECT  classrooms.name, 
    subjects.name, 
    concat(teachers.fname,' ',teachers.mname,' ',teachers.lname) as Teachers_name  
FROM    classrooms INNER JOIN
    subjects ON subjects.classroom_id=classrooms.classroomID  LEFT JOIN 
    teachers_subjects ON teachers_subjects.subject_id=subjects.subjectID LEFT JOIN
    teachers ON teachers_subjects.teacher_id=teachers.teacherID 

Have a look at this a article ( Introduction to JOINs – Basic of JOINs ) for a nice graphical introduction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM