【问题标题】:MySQL list entities and applying AND filter on joined tableMySQL 列出实体并在连接表上应用 AND 过滤器
【发布时间】:2019-01-04 22:26:42
【问题描述】:

有两个表:Person,House House 对 Person 有一个 FK,称为 person_id 房子有一个字段叫city

有没有办法在 city_a 和 city_b 中列出所有有房子的人?这应该排除在其中一个城市拥有房屋的人,但包括在两个城市以及其他城市都有房屋的人。

这是我当前的查询:

SELECT person.* 
FROM Person person 
JOIN House house ON house.person_id = person.id 
WHERE house.city IN ("city_a", "city_b");

但是,这个查询只返回在 city_a 或 city_b 有房子的人的列表,所以它不满足 AND 条件。

【问题讨论】:

    标签: mysql sql database join


    【解决方案1】:

    一个简单的方法使用 exists 。 . .两次:

    select p.*
    from person p
    where exists (select 1 from house h where h.person_id = p.id and h.city = 'city_a') and
          exists (select 1 from house h where h.person_id = p.id and h.city = 'city_b') ;
    

    如果您只想要此人的 id,那么 group byhaving 很方便:

    select h.person_id
    from house h
    where h.city in ('city_a', 'city_b')
    group by h.person_id
    having count(distinct h.city) = 2
    

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      相关资源
      最近更新 更多