我有一张名为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
答案 0 :(得分:2)
三种选择:
使用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。
使用不带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。
使用IN
:
SELECT *
FROM tution
WHERE subject_id=111
AND stud_id NOT IN (SELECT stud_id FROM tution WHERE subject_id= 333)
结果为SQL Fiddle。
结果:
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
答案 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)