从概念上讲,我会从Instructor
桌子开始,因为那是我想要返回的。
我会把它加入到Offering
桌子上,所以我有Offering
每个教练的所有东西。
(但我们根本不需要Instructor
表中的任何内容,因为我们在Offering
表中有 InstrId。)
然后我会加入到Enrollment
,基本上让所有注册了每个课程的学生。
然后我会加入到Student
. 但同样,我们真的不需要桌子上的任何东西Student
,我们已经stdId
在Enrollment
桌子上。
棘手的部分是 and 之间的Offering
连接Enrollment
。连接谓词必须是 onyear
和semester
,以及crsId
。
因此,为了满足规定的要求,只需要查询两个表:
SELECT e.stdId
, o.instrId
, e.year
FROM Offering o
JOIN Enrollment e
ON e.crsId = o.crsId
AND e.year = o.year
AND e.semester = o.semester
WHERE e.stdID = 'A01234567'
AND e.year >= 2006
AND e.year <= 2008
GROUP
BY e.stdId
, o.instrId
, e.year
ORDER
BY e.stdId
, o.instrId
, e.year
数据库设计有一个特殊性。考虑当有两名或更多教师在同一年和同一学期教授给定课程时会发生什么。
但这名学生只注册了其中一个。
此查询将获取两种产品的讲师。
这是查询的问题,但给定的数据库设计并没有给我们任何解决问题的方法......因为没有办法告诉学生有哪个讲师。
该查询满足规定的要求,但结果会有点奇怪,显示特定学生在 2006 年秋季有六位不同的“Calc I”讲师。
除非这里有什么东西在躲避我。
编辑:
As Emily Litella would have intoned, "Never mind...". There's a unique constraint on the Offering
table. There can be only one offering of a given crsId
in a semester. So there's no problem there. (Except that it's peculiar that there would be only one offering of a given course in a given semester.)
The GROUP BY
is not necessary. The constraints already guarantee that there will be no duplicate rows returned.
Actually, I think the GROUP BY is needed, because it's possible that the student was enrolled in two separate courses led by the same instructor. The purpose of the GROUP BY
is to eliminate any duplicate rows from the result set (as indicated in the specification.)