0

我有以下简化表格:

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

我想做一个查询,返回包含鸡肉和奶油的食谱的所有 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);  

这给了我:“错误 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);

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

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

4

3 回答 3

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");
于 2010-06-11T13:10:46.703 回答
0

其他建议很好,但这里有另一种方法。这实际上看起来就像您在查询中尝试执行的操作。虽然我不知道为什么当相同的信息(名称)似乎包含在“uses_ingredient”中时你有和“成分”表。

SELECT recipe_id, count(*) c FROM uses_ingredient
WHERE name="Chicken" OR name="Cream"
GROUP BY recipe_id
HAVING c=2
于 2010-06-11T13:26:35.410 回答
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
于 2010-06-10T12:34:43.443 回答