I have a Table which looks like this:
---------------------------
|housing_id | facility_id |
---------------------------
| 1 | 7 |
| 1 | 4 |
| 2 | 7 |
---------------------------
Now what i want to do is get all housing_ids with a facility_id of 7 AND 4.
So the query should only return the housing_id 1 in this case.
Database is mysql.
Another approach would be –
UPDATE – inspired by the comment by Josvic I decided to do some more testing and thought I would include my findings.
One of the benefits of using this query is that it is easy to modify to include more facility_ids. If you want to find all housing_ids that have facility_ids 1, 3, 4 & 7 you just do –
The performance of all three of these queries varies hugely based on the indexing strategy employed. I was unable to get reasonable performance, on my test dataset, from the dependant subquery version regardless of indexing used.
The self join solution provided by Tim performs very well given separate single column indices on the two columns but does not perform quite so well as the number of criteria increases.
Here are some basic stats on my test table – 500k rows – 147963 housing_ids with potential values for facility_id between 1 and 9.
Here are the indices used for running all these tests –
First query tested is the dependant subquery –
Next is my version using the GROUP BY … HAVING COUNT …
And last but not least the self join –