MySQL列表实体并在联接表上应用AND过滤器

时间:2019-01-04 22:26:43

标签: mysql sql database join

有两个表:Person,House 房子有一个FK到人称person_id 房子有一个叫做城市的领域

是否可以在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条件。

1 个答案:

答案 0 :(得分:0)

一个简单的方法使用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') ;

如果您只想获取此人的身份证,则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