I have four tables, assuming they have only an id as a column each.
listings
feature
location
l_f_location
as a junction table with FKs onlistingId
,featureId
,locationId
I try to query the l_f_location
table for a given set of locationIds
(logical AND match) and want as a result only those listings which match ALL the locationIds
, e.g. (7 AND 9 AND 10).
l_f_location
looks like
listingId featureId locationId
10 5 7
10 7 7
10 8 9
11 4 7
11 8 9
11 9 10
11 12 14
The goal is to retrieve only listingId
11 in this case - matching the set of locationIds
7, 9 and 10.
I tried the following query
"SELECT id, COUNT(*) as num FROM l_f_locations WHERE locationId IN ( 7, 9, 10) GROUP by listingId, locationId HAVING num = 3
"
But that gives wrong values of count as the grouping kicks in.
A similar query works perfectly on a simpler junction table e.g. only l_location with e.g. "SELECT id, COUNT(*) as num FROM l_location WHERE locationId IN ( 7, 9, 10) GROUP by listingId HAVING num = 3
".
Rgds, P.