嗨,我有一个看起来像这样的架构
我正在尝试进行这两个查询
找到在所有课程中其课程总人数最多的前4位讲师。
输出列:InstructorName,TotalEnrollment
排序方式:TotalEnrollment降序
列出所有由其他部门提供的先决条件的课程。
输出列:Course_id,Course_department,Prereq_id,Prereq_department
排序方式:Course_id升序
对于查询1,我写了
SELECT Instructor.i_id, Instructor.name, COUNT(Takes.s_id) AS totalEnrollment
FROM Instructor INNER JOIN Teaches
ON Instructor.i_id = Teaches.i_id
INNER JOIN Takes
ON Takes.course_id = Teaches.course_id
Group by Instructor.i_id, Instructor.name
ORDER BY totalEnrollment DESC;
对于查询2,我写了
SELECT Course.course_id, Course.dept_name, Prereq.prereq_id, Course.dept_name
FROM Course INNER JOIN Prereq
ON Course.course_id = Prereq.course_id
INNER JOIN Course
ON Course.course_id = Prereq.prereq_id
Order by Course.course_id ASC;
这些查询给出了输出,但这是错误的。我需要帮助以使查询正确
测试数据为 表文件是 tables
数据文件为 data
预期与我的输出
---- query 1 result:
10101 Srinivasan 11
45565 Katz 9
83821 Brandt 6
76766 Crick 2
15151 Mozart 1
12121 Wu 1
98345 Kim 1
22222 Einstein 1
32343 El Said 1
Query 1 Expected:
Srinivasan 10
Brandt 2
Katz 2
Crick 2
---- Query 2 result:
BIO-301 Biology BIO-101 Biology
BIO-399 Biology BIO-101 Biology
CS-190 Comp. Sci. CS-101 Comp. Sci.
CS-315 Comp. Sci. CS-101 Comp. Sci.
CS-319 Comp. Sci. CS-101 Comp. Sci.
CS-347 Comp. Sci. CS-101 Comp. Sci.
EE-181 Elec. Eng. PHY-101 Elec. Eng.
Query 2 Expected:
EE-181 Elec. Eng. PHY-101 Physics
答案 0 :(得分:0)
我认为您的第一个查询的问题是,您假设老师总是在每个学期教同一堂课,但是数据并不能说明这一点-因此,两位不同的老师教了CS-101,但您在数所有的学生都朝着两位老师的方向发展。在联接两个表时,您可能希望联接尽可能多的主键列,而不仅仅是它们之一。
尝试这个:
SELECT Instructor.i_id, Instructor.name, COUNT(Takes.s_id) AS totalEnrollment
FROM Instructor
INNER JOIN Teaches ON Instructor.i_id = Teaches.i_id
INNER JOIN Takes ON Takes.course_id = Teaches.course_id
AND Takes.sec_id = Teaches.sec_id -- added these 3 columnss
AND Takes.semester = Teaches.semester
AND Takes.year = Teaches.year
Group by Instructor.i_id, Instructor.name
ORDER BY totalEnrollment DESC;
对于第二个查询,当您两次连接同一张表时,您需要使用别名,并且您也没有做任何事情来检查“由其他部门提供”。
SELECT Course.course_id, Course.dept_name, Prereq.prereq_id, c2.dept_name
FROM Course
INNER JOIN Prereq
ON Course.course_id = Prereq.course_id
INNER JOIN Course c2 -- alias
ON c2.course_id = Prereq.prereq_id
AND c2.dept_name <> Course.dept_name -- prereq department is different
Order by Course.course_id ASC;
让我知道这些是否还有问题。