【发布时间】:2026-02-08 12:55:02
【问题描述】:
这是我正在尝试做的通用版本:
表recipes 具有字段id 和name。表 ingredients 包含字段 id、name 和 sweetness,以 1-10 的等级描述该成分的甜度。食谱有许多成分,成分在许多食谱中,因此两者在ingredients_recipes 表中相关,字段为ingredient_id 和recipe_id。
很容易找到包含甜度为 10 的成分的食谱。
SELECT DISTINCT recipes.* FROM recipes
INNER JOIN recipes_ingredients ri ON ri.recipe_id = recipes.id
INNER JOIN ingredients ON ingredients.id = ri.ingredient_id
WHERE ingredients.sweetness = 10
但是,我在否定该查询以查找具有 no 甜度 10 成分的食谱时遇到了麻烦。我的第一个想法是:
SELECT DISTINCT recipes.* FROM recipes
INNER JOIN recipes_ingredients ri ON ri.recipe_id = recipes.id
INNER JOIN ingredients ON ingredients.id = ri.ingredient_id
WHERE ingredients.sweetness != 10
但是,它会找到包含 任何 non-sweetness-10 成分的食谱。
我的下一次尝试如下,似乎可行:
SELECT * FROM recipes WHERE
(
SELECT count(*) FROM ingredients INNER JOIN recipes_ingredients ri ON
ri.ingredient_id = ingredients.id WHERE ingredients.sweetness = 10 AND
ri.recipe_id = recipes.id
) = 0
但是,我的一般经验是,与等效的、精心设计的 JOIN 相比,依赖子查询运行缓慢。我玩过加入、分组等,但不能完全理解它,特别是因为,虽然看起来 LEFT JOIN 和 IS NULL 是合适的工具,但有两个加入已经让事情变得很糟糕。很棒的 SQL 向导,我可以运行什么查询来获得最佳结果?谢谢!
【问题讨论】:
标签: mysql optimization join subquery