查询与多用途值有关系的记录

时间:2019-07-17 02:45:42

标签: sql sql-server-2008 many-to-many

如何与所有给定的学生一起查询参加同一课程的所有学生?


[Table:Students]
Id  Name
--- --------
1   S1
2   S2
3   S3
4   S4
5   S5

[Table:Course]
Id  Name
--- --------
1   CA
2   CB
3   CC

[Table:SC]
StudentId  CourseId
---------  ---------
1          1
2          1
3          1
4          1
1          2
2          2
5          2
1          3
3          3

我想知道谁与S1和S2处于同一路线,在上面给出的数据中,结果应该是S3,S4和S5,因为:

   S3,S4: attend CA, which has both S1&S2
   S5   : attend CB, which has both S1&S2

我已经尝试使用GROUP-BY-HAVING进行查询,但这看起来很丑:

SELECT *
FROM [Students]
WHERE [Id] IN
(
    SELECT [StudentId]
    FROM [SC]
    WHERE [CourseId] IN
    (
        SELECT [CourseId]
        FROM [SC]
        WHERE [StudentId] IN 
        (
            SELECT [Id] 
            FROM [Students]
            WHERE [Name] IN ('S1', 'S2') 
        )
        GROUP BY [CourseId]
        HAVING COUNT(1)=2
    )
)
AND [Name] NOT IN ('S1', 'S2') 

还有更好的方法吗?谢谢。

1 个答案:

答案 0 :(得分:1)

略有简化。基本原理与您相同。使用Course

查找与S1S2共同的exists
select  s.Name, sc.CourseId
from    SC sc
        inner join Students s   on  sc.StudentId    = s.Id
where   exists  
        (
            select  x.CourseId
            from    SC x
                    inner join Students y   on  x.StudentId = y.Id
            where   y.Name  in ('S1', 'S2')
            and     x.CourseId  = sc.CourseId
            group by x.CourseId
            having count(*) = 2
        )
and     s.Name  not in ('S1', 'S2')
order by s.Name