0

我在使用一个查询从表中选择正确数据时遇到问题。我不确定是否可以做到。

properties:
- id
- name

facilities:
- id
- name

property_facilities:
- property_id
- facility_id

正如您在上面的架构中看到的,每个属性都可以有一个或多个设施。在我的代码中的某个时刻,我需要有一个具有一些设施的属性 ID 列表。

伪 SQL:

SELECT property_id
FROM property_facilities
WHERE
  facility_id IN (8, 12)

显然这是行不通的,因为我需要一个具有设施 8 和 12 的属性 ID 列表,而不仅仅是其中一个。我怎么能做到这一点?

4

2 回答 2

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
于 2012-09-20T20:03:33.827 回答
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)
于 2012-09-20T20:05:21.757 回答