I have 3 tables: products, categories and pro_cat_link. A product can be linked to one or many categories through the table pro_cat_link.
My query must answer the following problem: find all products that match a set of categories. Ex: find all products that are "yellow AND fruit AND sweet".
When researching this problem in SO I could find only the solution what I'm currently using: Complicated SQL Query--finding items matching multiple different foreign keys
In my case, my query looks like this:
SELECT products.id, COUNT(DISTINCT categories.id) as countCat
FROM products
INNER JOIN pro_cat_link ON (pro_cat_link.product_id = products.id)
WHERE pro_cat_link.category_id IN (3,6,8,10)
GROUP BY product.id
ORDER BY product.date DESC
HAVING countCat = 4
In other words, select all products that match one of category ids (3,6,8,10) and keep only those that have exactly 4 categories matching.
This works well, but I'm running into performance issues as the COUNT(), GROUP BY, ORDER BY makes proper indexing very limited. Can anyone think of a better way to solve that problem?