如何使用两个带条件的表来选择查询

时间:2012-09-21 17:06:06

标签: mysql sql

我有2个表,Student_Record的表A和Student_ID字段链接的Student_Subject的表B.

Table A (Student_Record)
Student_ID | Name  | School_Year
1          | Jane  | 2010-2011
2          | Amy   | 2010-2011
3          | Dave  | 2011-2012
4          | Roger | 2010-2011


Table B (Student_Subject)
Student_ID | Subject | Grade
1          | Math    | Passed
1          | Physics | Passed
1          | History | Passed
2          | Math    | Failed
2          | Physics | Passed
2          | History | Passed
3          | Math    | Passed
3          | Physics | Passed
3          | History | Passed
4          | Math    | Passed
4          | Physics | Passed
4          | History | Passed


根据上面的示例表,我想选择2010 - 2011年注册的学生,并通过所有科目。

结果应该返回 Jane Roger ,因为他们通过了所有3个科目并且在2010-2011注册了 Amy < / strong>数学失败,戴夫,其学年是2011-2012。

1 个答案:

答案 0 :(得分:1)

select sr.Student_ID, sr.Name
from Student_Record sr
left outer join Student_Subject ss on sr.Student_ID = ss.Student_ID 
    and ss.Grade = 'Failed'
where ss.Student_ID is null
    and sr.School_Year = '2010-2011'

SQL Fiddle Example