Mysql intersect results

前端 未结 2 490
自闭症患者
自闭症患者 2021-01-21 13:56

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         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-21 14:44

    Normally you would do an intersection of the itemid‍s 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 itemid‍s where there is an id for all three id‍s.

    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)
    

提交回复
热议问题