使用 EXISTS:
SELECT
id, Recipe, Directions
FROM
recipes_tbl AS r
WHERE EXISTS
( SELECT *
FROM recipe_to_ingredient AS ri
JOIN ingredients_tbl AS i
ON i.id = ri.id_ingredient
WHERE ri.id_recipe = r.id
AND i.Ingredient = 'beef'
)
AND EXISTS
( SELECT *
FROM recipe_to_ingredient AS ri
JOIN ingredients_tbl AS i
ON i.id = ri.id_ingredient
WHERE ri.id_recipe = r.id
AND i.Ingredient = 'potatoes'
)
...
使用 JOIN:
SELECT
r.id, r.Recipe, r.Directions
FROM
recipes_tbl AS r
JOIN
recipe_to_ingredient AS ri1
ON ri1.id_recipe = r.id
JOIN
ingredients_tbl AS i1
ON i1.id = ri1.id_ingredient
AND i1.Ingredient = 'beef'
JOIN
recipe_to_ingredient AS ri2
ON ri2.id_recipe = r.id
JOIN
ingredients_tbl AS i2
ON i2.id = ri1.id_ingredient
AND i2.Ingredient = 'potatoes'
...
使用 GROUP BY:
SELECT
r.id, r.Recipe, r.Directions
FROM
recipes_tbl AS r
JOIN
recipe_to_ingredient AS ri
ON ri.id_recipe = r.id
JOIN
ingredients_tbl AS i
ON i.id = ri.id_ingredient
WHERE i.Ingredient IN ('beef', 'potatoes', ...)
GROUP BY r.id
HAVING COUNT(*) = @n --- number of items in above list
如果您已经有了成分的 ID,则无需加入 ingredients 表(在所有 3 个版本中)。
GROUP BY 解决方案的优势在于,您可以更改它以显示具有例如 “至少 5 种,共 7 种成分”的食谱,只需将 HAVING COUNT(*)=7 更改为 @ 987654330@。其他两种方式在这方面并不灵活。
但它们可能会更快,具体取决于您的表的大小、分布和您运行的查询(使用 2、3 或 20 种成分?)