1

我对 MYSQL 有一个问题,只能通过使用我不太擅长的内部连接来解决,我有四个表。

表1:教室 classicID、name、.......

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

表 3:科目 subjectID、姓名、classic_id、......

表 4 Teachers_subjects teacher_id 和 subject_id

我想要一个查询来获取所有班级名称(classrooms.name)及其所有科目名称(subjects.name),其中subjects.classroom_id=classrooms.classroomID

我还想获取教师的姓名(teachers.name),其中Teachers_subjects.subject_id = subject.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

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

谢谢

4

1 回答 1

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 

查看这篇文章(JOIN 简介 – JOIN 基础)以获得很好的图形介绍。

于 2013-08-19T17:32:43.637 回答