我有3个具有这种结构的表:
Recipe
id | recipe_name
Ingredients
id | ingredients_name
Relationship
rid | 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
但是我想要的是,当一个食谱仅包含鸡肉和蛋黄酱作为其成分时,它必须在单独的结果中显示。我怎样才能做到这一点?
通过添加一个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条款。)
COUNT(DISTINCT case
WHERE