我正在尝试为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名姓电子邮件schoolIDNum
1埃丝特乙b@hotmail.com 33
2托米大号l@hotmail.com 55
registrationID peopleIDNum sectionIDNum
22个1 40
23 2 41
sectionID courseIDNum districtIDNum
40个11 5
41 12 5
schoolID districtIDNum
33个5
55 5
答案 0 :(得分: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 here。