I\'m trying to do something like the PHP array_intersect
. I have the following table
CREATE TABLE `recipes_ingredients_items` (
`id` INTEGER(11) D
Normally you would do an intersection of the itemids of each id:
(SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 71)
INTERSECT
(SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 2)
INTERSECT
(SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 22)
This will only select those itemids where there is an id for all three ids.
But since MySQL does not support INTERSECT
, you need to use inner joins:
SELECT DISTINCT itemid FROM recipes_ingredients_items
INNER JOIN (SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 71) a USING (itemid)
INNER JOIN (SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 2) b USING (itemid)
INNER JOIN (SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 22) c USING (itemid)
Try this:
SELECT item_id
FROM recipes_ingredients_items
WHERE id IN (71, 2, 22)
GROUP BY item_id
HAVING COUNT(*) = 3