This type of problem is called relational division.
There are two common solutions:
First solution strings together the matching categories and compares to a fixed string:
SELECT p2c.product_id FROM oc_product_to_category p2c GROUP BY p2c.product_id HAVING GROUP_CONCAT(p2c.category_id SEPARATOR ',' ORDER BY p2c.category_id) = '1,2'
Second solution does a
JOIN
for each required value:SELECT p.product_id FROM oc_product p INNER JOIN oc_product_to_category p2c1 ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1) INNER JOIN oc_product_to_category p2c2 ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2)
I cover these solutions in my presentation SQL Query Patterns, Optimized. I found in my tests that the join solution is much better for performance.
@Tom's suggestion is right, here's what that would look like in a complete query:
SELECT p.product_id, GROUP_CONCAT(p2c3.category_id SEPARATOR ',') AS categories
FROM oc_product p
INNER JOIN oc_product_to_category p2c1
ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1)
INNER JOIN oc_product_to_category p2c2
ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2)
INNER JOIN oc_product_to_category p2c3
ON (p.product_id = p2c3.product_id)
GROUP BY p.product_id;
The DISTINCT
that @Tom suggests shouldn't be necessary, because your p2c table should have a UNIQUE constraint over (product_id, category_id).