0

有两个表:Person,House House 对 Person 有一个 FK,叫做 person_id House 有一个叫做 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 条件。

4

1 回答 1

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') ;

如果您只想要此人的 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
于 2019-01-04T22:29:12.917 回答