我正在努力寻找可以报名参加课程的剩余学生。为此,我需要找到目前活跃且目前不在课程中的学生。我认为我写的查询是不正确的,因为当我运行查询时,它会一直显示一组空的结果,如何才能找到能够参加课程的剩余学生?
以下是当前查询:
SELECT st.StudentId, StudentAlias, StudentForename, StudentSurname
FROM Course c
INNER JOIN Student_Course sc
ON c.CourseId = sc.CourseId
INNER JOIN Student st
ON sc.StudentId = st.StudentId
WHERE (c.CourseId = 1 AND
sc.StudentId IS NULL
AND st.Active = 1)
ORDER BY st.StudentAlias
以下是表格:
学生:(所有学生名单)
StudentId StudentAlias StudentForename StudentSurname Active
1 u09382 James Smith 1
2 u83923 John Brooks 1
3 u38292 Karen Bradshaw 0
4 u20039 Chris Cameron 1
5 u39399 Jane Fields 1
课程:(所有课程列表)
CourseId CourseNo CourseName
1 INFO121 ICT
2 BUS122 Business and Finance
3 ENG432 English Language
Student_Course:(参加各自课程的学生名单)
StudentId CourseId
1 1
1 3
2 1
4 2
5 2
因此,例如,如果我选择CourseId = 1
,那么它应该显示有效但但显然不在CourseId = 1
的学生,这意味着它应该向下方显示这些学生注册课程的可能性:< / p>
4 - Chris Cameron
5 - Jane Fields
答案 0 :(得分:2)
尝试此查询
SELECT s.studentId, s.Forename
FROM Student s
WHERE s.studentId NOT IN (SELECT studentId
FROM Student_Course c WHERE c.courseId = 1) AND s.Active = 1
内部子查询返回courseId = 1的学生,在外部查询中我们过滤那些学生。
答案 1 :(得分:1)
试试这个
SELECT st.StudentId, StudentAlias, StudentForename, StudentSurname
FROM Course c
INNER JOIN Student_Course sc
ON c.CourseId = sc.CourseId
INNER JOIN Student st
ON sc.StudentId = st.StudentId
WHERE (sc.CourseId <> 1
AND st.Active = 1)
ORDER BY st.StudentAlias
答案 2 :(得分:0)
要找到不在课程上的活跃学生,请选择以下内容: -
SELECT st.StudentId, StudentAlias, StudentForename, StudentSurname
FROM Student st
LEFT OUTER JOIN Student_Course sc ON sc.StudentId = st.StudentId
LEFT OUTER JOIN Course c ON c.CourseId = sc.CourseId
WHERE c.CourseId IS NULL
AND st.Active = 1
ORDER BY st.StudentAlias
如果你想检查没有参加特定课程的学生,那么
SELECT st.StudentId, StudentAlias, StudentForename, StudentSurname
FROM Student st
LEFT OUTER JOIN Student_Course sc ON sc.StudentId = st.StudentId
LEFT OUTER JOIN Course c ON c.CourseId = sc.CourseId AND CourseId = 1
WHERE c.CourseId IS NULL
AND st.Active = 1
ORDER BY st.StudentAlias
让课程检查ON条款