MySQL:使用所有给定成分查询获取食谱

时间:2010-06-10 10:54:00

标签: mysql mysql-error-1146 mysql-error-1248

我有以下简化表:

CREATE TABLE recipe(id int, name varchar(25));  
CREATE TABLE ingredient(name varchar(25));  
CREATE TABLE uses_ingredient(recipe_id int, name varchar(25));

我想创建一个查询,返回包含Chicken和Cream的食谱的所有id。

我试过了

SELECT recipe_id FROM uses_ingredient INNER JOIN  
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream")  
USING (name) GROUP BY recipe_id  
HAVING COUNT(recipe_id) >= (SELECT COUNT(*) FROM theme);  

它给了我:“ERROR 1248(42000):每个派生表必须有自己的别名” 也可能是错的。

接下来我试了

SELECT recipe_id FROM 
(SELECT * FROM ingredient WHERE name="Chicken" OR name="Cream") AS t 
INNER JOIN uses_ingredient USING (name) 
GROUP BY recipe_id HAVING 
COUNT(recipe_id)>= (SELECT COUNT(*) FROM t);

给出“ERROR 1146(42S02):表'recipedb.t'不存在”

我想避免创建临时表,包括使用ENGINE = MEMORY。

3 个答案:

答案 0 :(得分:0)

可能有更好的方法来思考它,但我认为答案是两组的交集:那些含有鸡肉的食谱和那些含有奶油的食谱。如果您简化的不仅仅是列数,这可能对您不起作用。但我用一些记录试了一下,看起来很好。

SELECT CH.Recipe_Id
FROM
  (SELECT Recipe_Id
  FROM Uses_Ingredient
  WHERE Name = 'Chicken') CH
INNER JOIN 
  (SELECT Recipe_Id
  FROM Uses_Ingredient
  WHERE Name = 'Cream') CR
  ON CR.Recipe_Id = CH.Recipe_Id

答案 1 :(得分:0)

我同意MJB;它是两组的交集。所以我只是得到两套,看看它们都是什么......

SELECT *
    FROM recipe
    WHERE EXISTS (SELECT *
                      FROM uses_ingredient
                      WHERE uses_ingredient.recipe_id = recipe.recipe_id AND
                            uses_ingredient.name      = "Chicken") AND
          EXISTS (SELECT *
                      FROM uses_ingredient
                      WHERE uses_ingredient.recipe_id = recipe.recipe_id AND
                            uses_ingredient.name      = "Cream");

答案 2 :(得分:0)

其他建议很好,但这是另一种方式。这实际上就像您在查询中尝试做的那样。虽然我不知道你为什么和“成分”表,当相同的信息(名称)似乎包含在“uses_ingredient”。

SELECT recipe_id, count(*) c FROM uses_ingredient
WHERE name="Chicken" OR name="Cream"
GROUP BY recipe_id
HAVING c=2