SQL Select:同一个表的子集

时间:2014-04-14 20:34:50

标签: sql subquery

我有三个相关的表(学生,班级,注册)(一个学生可以有多个注册,一个班可以有多个注册),我需要从中选择所有注册课程的学生(x,y,z)但不在班级(a,b,c)。如何构建我的查询来实现这一目标?

2 个答案:

答案 0 :(得分:1)

我不同意我们需要更多信息才能说实话。这样的事情应该有效。另一种方法是使用MINUS关键字来获取第一个查询(x,y和z类中的学生)的所有结果,但第二个查询的结果除外(a,b和c类中的学生) )。

选择所有x,y和z类以及a,b和c类的NONE中的所有学生。

SELECT * FROM Students s
WHERE EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'x')
AND EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'y')
AND EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId = 'z')
AND NOT EXISTS (SELECT * FROM Enrollment
    WHERE studentId = s.StudentId AND ClassId IN ('a', 'b', 'c')

答案 1 :(得分:1)

假设DDL(仅用于引入名称):

create table student ( s_id numeric, name varchar );
create table class ( c_id numeric, name varchar );
create table enrollment ( s_id numeric, c_id numeric );
  1. 选择不在a,b或c

    中的学生的ID
    select s_id from enrollments where c_id not in
        (select c_id from class where name in ('a', 'b', 'c');
    
  2. 在x,y或z中选择学生ID

    select s_id from enrollments where c_id in
        (select c_id from class where name in ('x', 'y', 'z');
    
  3. 合并

    select * from students where
        s_id in (select s_id from enrollments where c_id in
            (select c_id from class where name in ('x', 'y', 'z') and
        s_id not in (select s_id from enrollments where c_id in
            (select c_id from class where name in ('a', 'b', 'c');