I’m having problems selecting the right data from a table with one query. I’m
unsure if it can be done.
properties:
- id
- name
facilities:
- id
- name
property_facilities:
- property_id
- facility_id
As you can see in the schema above, each property can have one or more
facilities. At a certain point in my code I need to have a list of property ids
that have some facilities.
PSEUDO SQL:
SELECT property_id
FROM property_facilities
WHERE
facility_id IN (8, 12)
Obviously this doesn’t work, since I need to have a list of property ids that
have BOTH the facility 8 and 12, not just one of them. How could I achieve
this?
Adding a HAVING clause with the expected number of matching id’s will do it:
This does assume, however, that you have no duplicate entries in your
property_facilitiestable. If you do, you can fix this using DISTINCT in a subquery, or by simply adding constraints not to allow duplicates in the first place.Here’s the same query with a DISTINCT subquery: