在带有条件语句的多个表上使用左连接

时间:2013-08-19 17:28:14

标签: php mysql foreign-keys relational-database

我遇到了MYSQL的问题,只能通过使用我不太喜欢的内连接来解决,我有四个表。

表1:教室 课堂ID,姓名,.......

表2:教师 fname,mname,lname,.......

表3:科目 subjectID,name,classroom_id,.....

表4 Teachers_subjects teacher_id和subject_id

我想要一个查询来获取所有类名(classrooms.name)及其所有主题名称(subjects.name) subject.classroom_id = classrooms.classroomID

我还想得到老师的名字(teachers.name),其中Teachers_subjects.subject_id = subjects.subjectID 和Teachers_subjects.teacher_id = teachers.teacherID。

我目前正在使用此查询:

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

我得到了我想要的东西,但我希望获得所有课程及其相应的科目,即使它不在表teacher_subjects上。这是列出所有课程及其科目,即使该科目没有分配给任何教师。

由于

1 个答案:

答案 0 :(得分:2)

您可以尝试类似

的内容
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 

请看一篇文章(Introduction to JOINs – Basic of JOINs),以获得精彩的图形介绍。