选择没有特定值的ID

时间:2014-10-28 23:56:27

标签: mysql sql

我有一个包含以下架构的表格:

+---------+--------+
|studentId | course | 
+---------+--------+
|1        | 2      | 
|1        | 3      | 
|1        | 4      | 
|1        | 5      | 
|2        | 4      | 
|2        | 5      | 
+---------+--------+

我想执行查询以获得没有课程2和3的学生ID

select * from students where course not in (2,3);

但它会返回学生ID 1和2,我希望它只返回学生ID 2.

我该怎么做?

7 个答案:

答案 0 :(得分:2)

你可以这样做:

select * from students where studentId not in -- exclude all students from course 2 & 3
(
    --find all the students in course 2 & 3
    select distinct studentId --could be duplicates might as well grab a distinct list.
    from students 
    where course in (2,3)
)

答案 1 :(得分:2)

此答案假设OP想要筛选出课程2或课程3或两者都设置的学生。

首先,找到所有具有课程2或3的学生

SELECT DISTINCT studentId
FROM students
WHERE course IN (2,3)

然后,找到所有不在该列表中的学生

SELECT *
FROM students
WHERE studentId NOT IN (...)

如果您只想返回没有课程的studentIds列表,请将*替换为DISTINCT studentId

把它们放在一起:

SELECT DISTINCT studentId
FROM students
WHERE studentId NOT IN (
  SELECT DISTINCT studentId
  FROM students
  WHERE course IN (2,3)
)

答案 2 :(得分:1)

使用having过滤掉有课程2或3的学生的另一个查询

select studentId
from students
group by studentId
having sum(course in (2,3)) = 0

答案 3 :(得分:0)

这应该有效:

select
    *
from
    students s
where
    not exists ( select
                     1
                 from
                     students ss
                 where
                     ss.studentID = s.studentID
                     and ss.course in (2,3));  

答案 4 :(得分:0)

我建议使用NOT IN并为每个参加2或3课程的学生编写一个子查询。也就是说,如果你正在寻找没有参加2或3课程的学生。如果你想要排除正在学习BOTH课程的学生,这需要稍微改变一下。如果是这种情况,请告诉我。

首先编写子查询,这很容易:

SELECT * 
FROM students
WHERE course = 2 OR course = 3

然后,您可以使用NOT IN运算符再次从表中进行选择:

SELECT DISTINCT studentid
FROM students
WHERE studentid NOT IN (SELECT studentid
                        FROM students
                        WHERE course = 2 OR course = 3);

it works

答案 5 :(得分:0)

SELECT DISTINCT x.studentid 
           FROM student x
           LEFT 
           JOIN 
              ( SELECT studentid 
                  FROM student 
                 WHERE course IN(2,3) 
                 GROUP 
                    BY studentid 
                HAVING COUNT(*) = 2 ) y
             ON y.studentid = x.studentid
          WHERE y.studentid IS NULL;

(当然,持有学生和课程的表格不太可能被称为studentenrolment可能是更好的标题)

答案 6 :(得分:-1)

JR的查询表现不佳MySQL< 5.6并且仅在课程中执行OR而不是AND。

试试这个:

SELECT 
  id 
FROM foo AS missingfoo 
LEFT JOIN (
           SELECT id FROM foo AS foo1 
           JOIN foo AS foo2 USING (id) 
           WHERE foo1.course=2 
           AND foo2.course=3
          ) AS z 
USING (id) WHERE z.id IS NULL GROUP BY id;