查找仅包含给定成分的匹配行配方

时间:2016-11-11 15:12:45

标签: mysql sql

我在MySql RECIPESINGREDIENTSRECIPE_INGREDIENTS中有三个表。现在我想获取仅包含所提供的成分ID的配方。我简单的语言我想搜索我可以用我的成分制作的食谱。

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询来获取具有所有或部分指定成分的食谱的ID:

SELECT r.id
FROM Recipes AS r
INNER JOIN Recipe_ingredients AS ri ON r.id = ri.recipe_id
INNER JOIN Ingredients AS i ON i.id = ri.ingredient_id
WHERE i.id IN ( ... list of ids here ...)
GROUP BY r.id
HAVING COUNT(DISTINCT i.id) <= n -- where n is the number of the ingredient ids
                                 -- specified in the list of the where clause

修改:如果您想获得不包含指定列表中未包含的任何成分的食谱,则可以使用:

SELECT r.id
FROM Recipes AS r
LEFT JOIN Recipe_ingredients AS ri ON r.id = ri.recipe_id
LEFT JOIN Ingredients AS i ON i.id = ri.ingredient_id
WHERE i.id NOT IN ( ... list of ids here ...)
GROUP BY r.id
HAVING COUNT(i.id) = 0
相关问题