SQL查询:如何选择相关表中所有记录都具有特定属性值的记录

时间:2015-11-17 00:17:55

标签: sql

给出一个示例表定义:

school:
  school_id  |  school_name    
-------------+------------
     1       | school1
     2       | school2
     3       | school3

classroom:
classroom_id | has_projector | school_id      
-------------+---------------+-------------
     1       |     f         | 1
     2       |     f         | 1
     1       |     t         | 2
     2       |     t         | 2
     1       |     f         | 3
     2       |     t         | 3
     3       |     t         | 3

如何选择所有教室都有投影仪的学校? (在这种情况下,只能选择school2。)

我的想法是:

select school_name from school where 
school_id in (select school_id from classroom where has_projector='t') and 
school_id not in (select school_id from classroom where has_projector!='t');

它有效,但它是最佳解决方案吗? 有没有更好的方法来选择所要求的数据?

3 个答案:

答案 0 :(得分:1)

在学校id上离开学校到教室,投影仪等于假。然后只返回教室桌上学校ID为空的那些。

    SELECT school_name
    FROM school
    LEFT JOIN classroom
    ON school.school_id = classroom.school_id
    AND classroom.has_projector = 'f'
    WHERE classroom.school_id IS NULL

答案 1 :(得分:0)

我认为使用having子句的简单聚合更简单一些:

select s.school_id
from school s join
     classroom c
     on s.school_id = c.school_id
group by s.school_id
having sum(case when has_projector = 't' then 1 else 0 end) = count(*);

答案 2 :(得分:0)

    select distinct s.school_name
    from school s, classroom c
    where s.school_id = c.school_id
    and c.has_projector = 't'

这就像写它一样简单。

CK