简体   繁体   English

SQL如何在自联接上查询

[英]SQL how to query on self-join

A sql question confused me a lot, I have two tables like this 一个sql问题让我很困惑,我有两个这样的表

create table faculty
(fac No
 fac first name
 fac last name
 fac supervisor No)

another is 另一个是

create table offering
(offer No
 course No
 offterm
 offyear
 offlocation
 offime
 facNo   )

now I need to write a query that list the names of faculty members and the course number for which the faculty member teaches the same course as his or her supervisor in 2010. 现在,我需要编写一个查询,其中列出了教职员工的姓名以及该教职员工在2010年与其主管一起教授同一门课程的课程编号。

I try to write a query like this 我试着这样写一个查询

select fa.FacNo,fa.FacFirstName,fa.FacLastName
from faculty as fa,faculty as fs,Offering as o, Offering as os
where fa.FacSupervisor = fs.FacNo
and fa.FacNo = o.FacNo
and fa.FacSupervisor = os.FacNo
and o.OffYear = 2010

but I cant have the right answer, so please give me some hints 但我没有正确的答案,所以请给我一些提示

Thanks for every one, I worked it out as below 谢谢大家,我的工作如下

select f.FacFirstName,F.FacLastName,s.FacFirstName as SupFirstname,s.FacFirstName as        SupLasName,o.CourseNo
from faculty as f, Faculty as s ,Offering as o, Offering as os
where f.FacSupervisor = os.FacNo
and f.FacNo = o.FacNo
and o.CourseNo = os.CourseNo
and f.FacSupervisor = s.FacNo
and o.OffYear =2010 and os.OffYear =2010

I hope this is helpful for some new SQL leaner who faces the same issue . 我希望这对于一些面对相同问题的新SQL学习者有所帮助。

"so please give me some hints" “所以请给我一些提示”

Since that is you're question, I am happy to provide a hints. 既然是您的问题,我很乐意提供提示。

Make your joins explicit--it helps readability immensely. 使您的联接明确-极大地提高了可读性。 For example: 例如:

FROM faculty as fa
     INNER JOIN
     faculty as fs ON fa.FacSupervisor = fs.FacNo
     INNER JOIN
     Offering as o ON fa.FacNo = o.FacNo
     INNER JOIN
     Offering as os ON fs.FacNo = os.FacNo

Once you do that I suspect you'll have much better luck seeing any problems. 一旦这样做,我怀疑您遇到任何问题都会好运。 Or at elast if will be easier for us to help more. 或至少可以为我们提供更多帮助。

You then need to filter with 然后,您需要过滤

WHERE o.[course No] = os.[Course No]
  AND o.OffYear = 2010

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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