检索满足条件且不满足其他条件的记录

时间:2014-05-15 07:12:24

标签: mysql sql

我有一张名为tuition的桌子 我想要检索所有学习111和不学习333的学生 这是我能想到的:

http://www.sqlfiddle.com/#!2/f6411/3

stud_id | subject_id
--------------------
    1       111
    1       222
    2       222
    2       333
    3       111
    3       222
    3       333
    4       111
    4       222

输出

stud_id
-------
   1
   4 

4 个答案:

答案 0 :(得分:2)

三种选择:

  1. 使用HAVING子句和WHERE子句:

    SELECT *
    FROM tution 
    WHERE subject_id = 111 OR subject_id=333
    GROUP BY stud_id
    HAVING COUNT(DISTINCT subject_id)=1 AND subject_id<>333
    

    结果为SQL Fiddle

  2. 使用不带HAVING子句的WHERE子句:

    SELECT *
    FROM tution 
    GROUP BY stud_id
    HAVING COUNT(DISTINCT subject_id)=2 AND subject_id =111 AND subject_id<>333
    

    结果为SQL Fiddle

  3. 使用IN

    SELECT *
    FROM tution
    WHERE subject_id=111
    AND stud_id NOT IN (SELECT stud_id FROM tution WHERE subject_id= 333)
    

    结果为SQL Fiddle

  4. 结果:

    STUD_ID  SUBJECT_ID
    1        111
    4        111
    

答案 1 :(得分:1)

select stud_id from tution 
where stud_id not in (select stud_id from tution t 
                  where t.subject_id = 333) 
and subject_id = 111

Fiddle

答案 2 :(得分:0)

试试这个:

SELECT t1.stud_id FROM tuition t1 
WHERE t1.subject_id=111 
AND NOT EXISTS(SELECT 1 FROM tuition t2 
               WHERE t1.stud_id=t2.stud_id 
               AND t2.subject_id = 333)

答案 3 :(得分:0)

以下显示满意给定条件的所有独特学生。

SELECT Distinct stud_id
FROM tution
WHERE subject_id=111
AND 
stud_id NOT IN (SELECT stud_id FROM tution WHERE subject_id= 333)