我正在使搜索引擎可以使用过滤器。
我的SQL看起来像这样;
SELECT l.location_id, og.*,f.*
FROM object_types ot
LEFT JOIN object_group_types ogt ON ogt.object_type_id = ot.object_type_id
LEFT JOIN object_groups og ON og.object_group_type_id = ogt.object_group_type_id
LEFT JOIN object_groups2filters og2f ON og2f.object_group_id = og.object_group_id
LEFT JOIN filters f ON f.filter_id = og2f.filter_id
LEFT JOIN locations l ON l.location_id = og.location_id
WHERE ot.object_type_key = 'TYPE_TENNIS';
现在基于用户过滤器输入,我想为其选择正确的位置。 但是因为我将所有内容都用LEFT JOIN连接,所以所有过滤器项都位于不同的行中,请参见图片。
所以我想选择一个location_id同时具有filter_key FILTER_GRASS和FILTER_PARKING的位置。
如果我使用“ AND f.filter_key ='FILTER_PARKING'AND f.filter_key ='FILTER_GRASS'”,则将无法正常工作,因为过滤器值位于单独的行中。
任何人都有线索来选择location_id具有两个filter_keys的位置吗?
答案 0 :(得分:2)
您需要将Group By
与Having
结合使用,以过滤出位置。
尝试:
SELECT l.location_id
FROM object_types ot
LEFT JOIN object_group_types ogt ON ogt.object_type_id = ot.object_type_id
LEFT JOIN object_groups og ON og.object_group_type_id = ogt.object_group_type_id
LEFT JOIN object_groups2filters og2f ON og2f.object_group_id = og.object_group_id
LEFT JOIN filters f ON f.filter_id = og2f.filter_id
LEFT JOIN locations l ON l.location_id = og.location_id
WHERE ot.object_type_key = 'TYPE_TENNIS'
GROUP BY l.location_id
HAVING SUM(f.filter_key = 'FILTER_PARKING') AND
SUM(f.filter_key = 'FILTER_GRASS')
答案 1 :(得分:0)
您可以使用in
和条件聚合
SELECT l.location_id
FROM object_types ot
LEFT JOIN object_group_types ogt ON ogt.object_type_id = ot.object_type_id
LEFT JOIN object_groups og ON og.object_group_type_id = ogt.object_group_type_id
LEFT JOIN object_groups2filters og2f ON og2f.object_group_id = og.object_group_id
LEFT JOIN filters f ON f.filter_id = og2f.filter_id
LEFT JOIN locations l ON l.location_id = og.location_id
WHERE ot.object_type_key = 'TYPE_TENNIS'
and f.filter_key in ('FILTER_PARKING','FILTER_GRAS')
GROUP BY l.location_id
HAVING SUM(case when f.filter_key = 'FILTER_PARKING' then 1 else 0 end)>=1 AND
SUM(case whenf.filter_key = 'FILTER_GRAS' then 1 else 0 end)>=1