Mysql交叉结果

时间:2010-10-10 08:40:09

标签: php mysql

我正在尝试做类似PHP 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';  

我需要一个查询,它会将包含id为2,72,64的所有结果作为不同的itemid。问题是id可能在itemid中不止一次存在,即itemid 600可能有3行,其中有与其相关的ID 2,100,2。 我的想法是查询说x number o子查询返回结果并执行类似PHP array_intersect的操作,从而返回具有所有这些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)

这就是我得到的,这是100%的错误。

2 个答案:

答案 0 :(得分:5)

试试这个:

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

答案 1 :(得分:2)

通常你会对每个 id itemid 进行交集:

(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)

这将只选择那些 itemid ,其中所有三个 id id

但由于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)