I am working on a project where I'd like to display products that are subject to certain filters. Let's say I have the following 2 tables:
Products
id name
--------------
1 'Product 1'
2 'Product 2'
Filters
product_id filter_id
----------------------
1 a
1 b
2 a
I'm trying to write a query that only returns products if the filters are set. So if filter 'a' is active the results should be product 1 and 2, and if 'a' AND 'b' are active it should ONLY return product 1.
I've tried:
SELECT p.id
FROM products p
LEFT JOIN filters f ON f.product_id = p.id
WHERE filter.id = 'a'
GROUP BY p.id
This returns the id's for product 1 and 2 as expected. However, when I try:
SELECT p.id
FROM products p
LEFT JOIN filters f ON f.product_id = p.id
WHERE filter.id = 'a' AND filter.id = 'b'
GROUP BY p.id
I'd expect it to return the id for product 1, but it returns no results. How can I rewrite my query so that I get the product id's for the active filters? Can this be done with MySQL alone or do I have to loop through the results with php?