我有四个表,假设它们每个只有一个id。
listings
feature
location
l_f_location
作为与listingId
,featureId
,locationId
我尝试在l_f_location
表中查询给定的一组locationIds
(逻辑AND匹配),并且只希望结果匹配所有locationIds
的列表,例如l_f_location
。 (7和9和10)。
listingId featureId locationId
10 5 7
10 7 7
10 8 9
11 4 7
11 8 9
11 9 10
11 12 14
看起来像
listingId
目标是在这种情况下仅检索locationIds
11 - 匹配SELECT id, COUNT(*) as num FROM l_f_locations WHERE locationId IN ( 7, 9, 10) GROUP by listingId, locationId HAVING num = 3
7,9和10的集合。
我尝试了以下查询
“SELECT id, COUNT(*) as num FROM l_location WHERE locationId IN ( 7, 9, 10) GROUP by listingId HAVING num = 3
”
但是当分组开始时,这会给出错误的计数值。
类似的查询在更简单的联结表上完美地工作,例如只有l_location与例如“{{1}}”。
RGDS, P上。
答案 0 :(得分:3)
我假设相同的listingId
和locationId
可以有多个featureId
s?否则它会更容易。
如果是这种情况:
SELECT listingId, COUNT(*) as num
FROM
(SELECT DISTINCT listingId, locationId
FROM l_f_locations
WHERE locationId IN ( 7, 9, 10)) AS sub
GROUP by listingId, HAVING num = 3