SQL查询,多个JOIN和SELECT(?)语句

时间:2015-11-12 10:17:05

标签: sql select join

我已经查看了很多答案,并在代码中尝试了不同的选项,但我无法得到我需要的结果或查询根本不起作用。所以不得不寻求帮助。

这是一个学校实验室的任务,但本周我生病了,所以错过了向老师提问的机会,现在截止日期和更多类似的任务是本周末,所以不得不弄清楚

我需要结合三张桌子。没问题,但是从同一张桌子(教师)我需要获得每个课程的教师姓名以及课程的顾问老师(来自主题)。

这两个查询分开工作,但我无法弄清楚将它们合二为一的方法。

--displays all courses (its number, implementation, name) and teachers on the course
SELECT Course.subjectnumb, Course.coursenumb, Subject.subjectname, Course.participants, Teacher.firstname, Teacher.surname
FROM Course JOIN  Subject on Course.subjectnumb = Subject.subjectnumb  
JOIN Teacher on Course.teachernumb = Teacher.teachernumb  
ORDER BY Subject.subjectname ASC, Course.coursenumb ASC, Teacher.surname ASC

--display advisors names
SELECT teacher.firstname, teacher.surname 
FROM subject JOIN teacher ON teacher.teachernumb = subject.advisor 
ORDER BY teacher.surname ASC, teacher.firstname ASC

1 个答案:

答案 0 :(得分:1)

您可以在同一张桌子上加入两次。例如:

SELECT C.subjectnumb, C.coursenumb, 
       S.subjectname, C.participants, 
       TC.firstname as course_teacher_firstname, TC.surname as course_teacher_surname, 
       TS.firstname as subject_advisor_firstname, TS.surname as subject_advisor_surname, 
FROM Course C JOIN  Subject S on C.subjectnumb = S.subjectnumb  
JOIN Teacher TC on C.teachernumb = TC.teachernumb  
JOIN Teacher TS on S.advisor = TS.teachernumb 
ORDER BY S.subjectname ASC, C.coursenumb ASC, TC.surname ASC