0

我正在尝试为districtIDNum = 5已完成courseIDNum=11或的人获取数据courseIDNum=12,但不能同时完成两者。

但是,在我执行查询后,它返回了所有地区。我做错了什么?请帮助,并提前感谢!

SELECT p.FirstName, p.LastName, p.Email, s.CourseIDNum
FROM People p
INNER JOIN Registration r
 on p.PeopleID = r.PeopleIdNum
INNER JOIN Section s
 on r.SectionIDNum = s.SectionID
INNER JOIN School sc
 on p.SchoolIDNum = sc.SchoolID
WHERE (s.CourseIDNum=11 AND s.CourseIDNum!=12)
  OR (s.CourseIDNum!=11 AND s.CourseIDNum=12)
  AND s.DistrictIDNum=5
  AND r.Completed='Y'

以下是涉及的表格:

peopleID FirstName LastName Email schoolIDNum
1 Esther B b@hotmail.com 33
2 Tommy L l@hotmail.com 55

注册ID peopleIDNum sectionIDNum
22 1 40
23 2 41

sectionID courseIDNum 地区IDNum
40 11 5
41 12 5

schoolID 地区IDNum
33 5
55 5

4

1 回答 1

2

要仅返回参加过其中一门课程但不同时参加两门课程的人,请尝试:

SELECT max(p.FirstName), 
       max(p.LastName), 
       max(p.Email), 
       max(s.CourseIDNum)
FROM People p
INNER JOIN Registration r
 on p.PeopleID = r.PeopleIdNum
INNER JOIN Section s
 on r.SectionIDNum = s.SectionID
INNER JOIN School sc
 on p.SchoolIDNum = sc.SchoolID
WHERE s.CourseIDNum IN (11, 12)
   AND s.DistrictIDNum = 5
   AND r.Completed='Y'
group by p.PeopleID
having count(distinct s.CourseIDNum)=1

SQLFiddle在这里

于 2013-05-20T18:30:56.897 回答