如果已经给出了所有成分,则显示食谱名称

时间:2012-02-13 07:55:34

标签: mysql sql

我有3个具有这种结构的表:

配方

id | recipe_name

成分

id | ingredients_name

关系

摆脱| recipe_id | ingredients_id

示例我使用“鸡肉”和“蛋黄酱”的成分搜索食谱,然后它将显示具有这两种成分的所有食谱。我已经得到了代码:

SELECT * from recipe r
INNER JOIN relationship ri on r.id=ri.recipe_id
INNER JOIN ingredients i on i.id=ri.ingredients_id
WHERE i.ingredients_name IN ('chicken','mayonnaise')
GROUP BY r.id

但我想要的是,当食谱中只含有鸡肉和蛋黄酱作为其成分时,它必须显示在单独的结果上。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

我们需要跳过所有含有鸡肉和蛋黄酱以外成分的食谱,所以下面的内容应该有效:

SELECT * from recipe r
INNER JOIN relationship ri on r.id=ri.recipe_id
INNER JOIN ingredients i on i.id=ri.ingredients_id
WHERE i.ingredients_name IN ('chicken','mayonnaise')
and r.id not in (select r.id from recipe r
INNER JOIN relationship ri on r.id=ri.recipe_id
INNER JOIN ingredients i on i.id=ri.ingredients_id
WHERE i.ingredients_name not IN ('chicken','mayonnaise'))

答案 1 :(得分:1)

通过添加HAVING子句 - 如下所示:

SELECT * from recipe r
INNER JOIN relationship ri on r.id=ri.recipe_id
INNER JOIN ingredients i on i.id=ri.ingredients_id
GROUP BY r.id
HAVING COUNT(DISTINCT i.ingredients_name)=2 AND
       COUNT(DISTINCT case when i.ingredients_name IN ('chicken','mayonnaise') 
                           then i.ingredients_name end)=2

(注意:这将返回包括鸡肉和蛋黄酱,而不包含其他成分的食谱。要返回包含鸡肉和蛋黄酱的食谱,但也可能包含其他成分,请删除COUNT(DISTINCT case条件并恢复WHERE子句。)