1

我在找出解决这个问题的正确方法时遇到了一些麻烦。

Database tables:
Student(stdID[pk], stdName, stdSet)
Enrollment(stdID[pk], crsID[pk], year[pk], semester[pk], grade)
Offering(crsID[pk], year[pk], semester[pk], instrID)
Course(crsID[pk], crsTitle, creditHrs)
Instructor(instrID[pk], instrName, dept)

“查找从 2006 年到 2008 年教过给定学生 A01234567 的所有讲师。列出学生 ID、讲师 ID 和年份。不要重复行。”

我最初拥有的是这样的:

SELECT DISTINCT stdID, instrID, year
FROM Student s
JOIN Instructor i ON Offering o (o.instrID = i.instrID)
JOIN Offering o ON Course c (c.crsID = o.crsID)
WHERE stdID = 'A01234567'
    AND date BETWEEN (2006 AND 2008);

然而,这并不完全正确。我注意到这与“提供连接中缺少 2 列”有关,但我不知道这意味着什么......

4

2 回答 2

2

您的连接语法不正确。这是您的查询,已修复,因此至少在语法上是正确的。这可能会帮助您找到解决方案:

SELECT DISTINCT stdID, instrID, year
FROM Instructor i JOIN
     Offering o
     ON o.instrID = i.instrID join
     Course c
     on c.crsID = o.crsID
WHERE stdID = 'A01234567' AND date BETWEEN (2006 AND 2008);
于 2012-12-11T00:00:36.010 回答
1

从概念上讲,我会从Instructor桌子开始,因为那是我想要返回的。

我会把它加入到Offering桌子上,所以我有Offering每个教练的所有东西。

(但我们根本不需要Instructor表中的任何内容,因为我们在Offering表中有 InstrId。)

然后我会加入到Enrollment,基本上让所有注册了每个课程的学生。

然后我会加入到Student. 但同样,我们真的不需要桌子上的任何东西Student,我们已经stdIdEnrollment桌子上。

棘手的部分是 and 之间的Offering连接Enrollment。连接谓词必须是 onyearsemester,以及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.)

于 2012-12-11T00:41:41.787 回答