仅当Table_B中存在的所有关联记录都符合特定条件时,才从Table_A中获取记录

时间:2019-01-11 06:06:41

标签: sql-server

例如: 有两个表:

  1. 表1-老师
  2. 表2-学生

在“教师”表中,它包含教师的详细信息

Teacher_Id  &thinsp;    Teacher_Name<br/>
1   &emsp; &emsp;  &emsp; &emsp;    Akshay<br/>
2   &emsp; &emsp; &emsp;  &emsp;    Rohan<br/>
3   &emsp; &emsp;  &emsp; &emsp;    Suresh<br/>
4   &emsp;  &emsp; &emsp;  &emsp;   Naresh<br/>

在“学生”表中,包含学生的详细信息

Student_Id &thinsp; Student_Name&thinsp;    Teacher_Id&thinsp;  Marks<br/>
1&emsp; &emsp;  &emsp; &emsp;   Abhi&emsp; &emsp;  &emsp; &emsp;    1&emsp; &emsp;  &emsp; &emsp;   50<br/>
2&emsp; &emsp;  &emsp; &emsp;   Kumar&thinsp; &emsp;  &emsp; &emsp; 2&emsp; &emsp;  &emsp; &emsp;   28<br/>
3&emsp; &emsp;  &emsp; &emsp;   Rahul&thinsp; &emsp;  &emsp; &emsp; 2&emsp; &emsp;  &emsp; &emsp;   90<br/>
4&emsp; &emsp;  &emsp; &emsp;   Mohan&thinsp; &emsp;  &emsp; &emsp; 4&emsp; &emsp;  &emsp; &emsp;   39<br/>
5&emsp; &emsp;  &emsp; &emsp;   Anil&emsp; &emsp;  &emsp; &emsp;    3&emsp; &emsp;  &emsp; &emsp;   51<br/>
6&emsp; &emsp;  &emsp; &emsp;   Jack&emsp; &emsp;  &emsp; &emsp;    4&emsp; &emsp;  &emsp; &emsp;   38<br/>
7&emsp; &emsp;  &emsp; &emsp;   Daniel&ensp; &emsp;  &emsp; &emsp;  2&emsp; &emsp;  &emsp; &emsp;   78<br/>
8&emsp; &emsp;  &emsp; &emsp;   Arun&emsp; &emsp;  &emsp; &emsp;    3&emsp; &emsp;  &emsp; &emsp;   66<br/>
9&emsp; &emsp;  &emsp; &emsp;   Mark&emsp; &emsp;  &emsp; &emsp;    1&emsp; &emsp;  &emsp; &emsp;   43<br/>
10&ensp; &emsp;  &emsp; &emsp;  Mukesh&ensp; &emsp;  &emsp; &emsp;  4&emsp; &emsp;  &emsp; &emsp;   99<br/>

您会看到一位老师与多名学生相关联。 我想挑选所有学生都通过考试的老师(及格分数为40)。 例如:教师为Teacher_Id = 2的老师与3个成绩分别为28、90、78的学生相关联。成绩为28的学生考试不及格。因此,我们不会选择那个老师。我们不会选择那些只有一个学生分数低于40分的老师。我们必须选择所有学生得分都超过40分的老师。

1 个答案:

答案 0 :(得分:0)

我们可以在此处使用条件聚合:

SELECT
    t.Teacher_Name,
    t.Teacher_Id
FROM Teacher t
INNER JOIN Student s
    ON t.Teacher_Id = s.Teacher_Id
GROUP BY
    t.Teacher_Name,
    t.Teacher_Id
HAVING
    COUNT(CASE WHEN s.Marks < 40 THEN 1 END) = 0;

另一个选项使用EXISTS

SELECT
    t.Teacher_Name,
    t.Teacher_Id
FROM Teacher t
WHERE NOT EXISTS (SELECT 1 FROM Student s
                  WHERE t.Teacher_Id = s.Teacher_Id AND s.Marks < 40);