I'm currently trying to build a MySQL (version 8) query to get a list of filters with an article count. I know I can use Elasticsearch to achieve the desired result, but the requirement is to use MySQL.
Data
Query
SELECT sf.name, sff.title, sff.key, COUNT(DISTINCT sfa.id) AS articles_count
FROM shop_filters AS sf
INNER JOIN shop_filter_facets AS sff ON sff.filter_id = sf.id
LEFT JOIN shop_facetables AS sfa ON (
sfa.facet_id = sff.id AND sfa.facetable_id IN (
SELECT sfa.facetable_id
FROM shop_filter_facets AS sff
INNER JOIN shop_facetables AS sfa ON sfa.facet_id = sff.id
INNER JOIN shop_filters AS sf ON sf.id = sff.filter_id
GROUP BY sfa.facetable_id
HAVING (
sf.name = 'filter_1' AND MAX(sff.key = 1252884110) = 1
OR MAX(sff.key = 1741157870) = 1
)
)
)
GROUP BY sf.name, sff.title, sff.key
Output
As you can see, the other filter_1 items have a count of 0. They should display a count higher than zero. What am I missing in the query above?
Expected output
An example of how the faceted search should behave:


