代码之家  ›  专栏  ›  技术社区  ›  mbouclas

Mysql intersect结果

  •  2
  • mbouclas  · 技术社区  · 14 年前

    array_intersect . 我有下表

    CREATE TABLE `recipes_ingredients_items` (
      `id` INTEGER(11) DEFAULT NULL,
      `itemid` INTEGER(11) DEFAULT NULL,
      `orderby` TINYINT(4) NOT NULL,
      KEY `id` (`id`),
      KEY `itemid` (`itemid`)
    )ENGINE=MyISAM
    AVG_ROW_LENGTH=47 CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';  
    

    我需要一个查询,该查询将获取包含say id 2,72,64的所有结果作为一个独立的itemid。问题是一个id可能在一个itemid中存在不止一次,即itemid 600可能有3行ids 2100,2行与其相关。
    ,从而返回具有所有这些ID的itemID。

    SELECT DISTINCT itemid  FROM recipes_ingredients_items
    WHERE 
    id IN (SELECT DISTINCT itemid FROM recipes_ingredients_items WHERE id = 71) 
    AND 
    id IN (SELECT DISTINCT  itemid FROM recipes_ingredients_items WHERE id = 2)
    AND 
    id IN (SELECT DISTINCT  itemid FROM recipes_ingredients_items WHERE id = 22)
    

    2 回复  |  直到 14 年前
        1
  •  2
  •   Gumbo    14 年前

    项目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)
    

    这只会选择那些 项目ID 在那里有一个 身份证件 三个人 s。

    但是由于MySQL不支持 INTERSECT ,则需要使用内部联接:

    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)
    
        2
  •  5
  •   Mark Byers    14 年前

    SELECT item_id
    FROM recipes_ingredients_items
    WHERE id IN (71, 2, 22)
    GROUP BY item_id
    HAVING COUNT(*) = 3