Mysql intersect results

前端 未结 2 489
自闭症患者
自闭症患者 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)
    
    0 讨论(0)
  • 2021-01-21 15:02

    Try this:

    SELECT item_id
    FROM recipes_ingredients_items
    WHERE id IN (71, 2, 22)
    GROUP BY item_id
    HAVING COUNT(*) = 3
    
    0 讨论(0)
提交回复
热议问题