Tables :
-- products --
id
-- categories --
id
-- products_categories --
id
product_id
category_id
What could be a SQL query that returns all the products IDs that matches ALL a given list of category_ids ?
Example : Given the list (3, 4, 5) I would like all product_ids that have AT LEAST (could be more) the category id 3 and the category id 4 and the category id 5 ?
Use:
This is popularly known as Celko’s division.
The
COUNT(DISTINCT c.id)must equal the number of values specified in theINclause. Otherwise, duplicates of 4/3/5/etc would be false positives. However, if all the pairs ofproduct_id, category_idare guaranteed to be unique,DISTINCTcan be omitted.