选择与多个条件匹配的行

时间:2016-11-06 10:38:00

标签: sql

我有一张表pupil_teachers就像这样

+------+----------+------------+
| id   | pupil_id | teacher_id |
+------+----------+------------+
| 1    | 100      | 200        | 
| 2    | 101      | 200        |  
| 3    | 102      | 200        |
| 4    | 102      | 201        |
| 5    | 101      | 201        |
| 6    | 101      | 202        | 
| 7    | 103      | 200        | 
+------+----------+------------+

查询将是检索学生100,101和102共有的所有教师。所以在这种情况下,它只能是身份200的老师。

Pupil 103也有ID为200的老师,但不是查询的一部分,我只想查询学生100,101和102.

所以它将从:

开始
SELECT teacher_id
FROM pupil_teachers
WHERE 

我真的不知道接下来要去哪里。显然以下是不正确的

SELECT teacher_id
FROM pupil_teachers
WHERE pupil_id IN (100, 101, 102)

1 个答案:

答案 0 :(得分:4)

以下是使用Group ByHaving子句

的一种方法
SELECT teacher_id
FROM pupil_teachers
WHERE pupil_id IN (100, 101, 102)
Group by teacher_id
Having Count(Distinct pupil_id) = 3

另一种方式

SELECT teacher_id
FROM pupil_teachers
Group by teacher_id
Having Count(Case when pupil_id  = 100 then 1 end) > 0  
   AND Count(Case when pupil_id  = 101 then 1 end) > 0 
   AND Count(Case when pupil_id  = 102 then 1 end) > 0