0

我正在努力寻找可以报名参加课程的剩余学生。为此,我需要找到当前活跃且当前不在课程中的学生。但是我认为我正在编写的查询不正确,因为当我运行查询时它一直显示一组空结果我如何才能找到能够注册该课程的剩余学生?

以下是当前查询:

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这意味着它应该在下面显示这些学生,以便有可能注册课程:

4 - Chris Cameron
5 - Jane Fields
4

3 回答 3

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 的学生,在外部查询中我们过滤这些学生。

于 2013-03-01T11:04:14.823 回答
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
于 2013-03-01T10:59:12.900 回答
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子句中

于 2013-03-01T11:02:01.157 回答