我在使用一个查询从表中选择正确的数据时遇到问题。我 不确定是否可以做到。
properties:
- id
- name
facilities:
- id
- name
property_facilities:
- property_id
- facility_id
正如您在上面的架构中所看到的,每个属性都可以包含一个或多个 设备。在我的代码中的某个点,我需要有一个属性id列表 有一些设施。
PSEUDO SQL:
SELECT property_id
FROM property_facilities
WHERE
facility_id IN (8, 12)
显然这不起作用,因为我需要有一个属性ID列表 同时拥有8号和12号设施,而不仅仅是其中之一。我怎么能实现 此?
答案 0 :(得分:2)
添加具有预期匹配ID数的HAVING子句将执行此操作:
SELECT property_id
FROM property_facilities
WHERE facility_id IN (8, 12)
GROUP BY property_id
HAVING count(facility_id) = 2
但是,这确实假设您的property_facilities
表中没有重复的条目。如果这样做,您可以在子查询中使用DISTINCT解决此问题,或者只是添加约束而不是首先允许重复。
这是与DISTINCT子查询相同的查询:
SELECT property_id
FROM (SELECT DISTINCT property_id, facility_id FROM property_facilities) distinct_rows
WHERE facility_id IN (8, 12)
GROUP BY property_id
HAVING count(facility_id) = 2
答案 1 :(得分:0)
怎么样
从property_id中的属性中选择property_id (从property_facilities中选择property_id)
这将生成所有具有任何设施的属性ID的列表,而不仅仅是8或12
编辑:如果您正在尝试获取包含设施8和12的属性列表,则可以执行以下操作:
select property_id from properties where property_id in
(select property_id from property_facilities where facility_id = 8) and property_id in
(select property_id from property_facilities where facility_id = 12)