SQL关联实体问题
我有一个 SQL 问题。我正在使用以下一组表格:
https://i.sstatic.net/HzRyl.png
Recipe 表包含 5 个菜谱,Ingredient 包含很多配料(52 个),IngredientList 是一个关联实体,是 Recipe 和 Ingredient 之间多对多关系的实现。 RecipeID 和 IngredientID 本质上是自动递增的 ID 号。
我正在尝试编写一个查询来显示所有素食食谱(即没有
'%beef%',
'%pork%',
'%chicken%',
'%lamb%
任何关联的 Ingredient.Name 的食谱)。我遇到的问题是结果集包含每种成分一行,而不是每个配方一行。
生成此结果集的查询是(请注意,成分表在此处被命名为成分):
SELECT recipe.name AS Dish, ingredients.name
FROM (recipe JOIN ingredientlist ON recipe.recipeid=ingredientlist.recipeid
JOIN ingredients ON ingredientlist.ingredientid=ingredients.ingredientid)
WHERE ingredients.name NOT LIKE '%beef%'
AND ingredients.name NOT LIKE '%chicken%'
AND ingredients.name NOT LIKE '%pork%'
AND ingredients.name NOT LIKE '%lamb%';
该查询生成 50 个结果(不是 52 个,因为根据成分.name 排除了两种成分,其中包含我的 WHERE 子句排除的 a 子字符串) 。
我的目标是返回菜谱表中 5 个菜谱名称中的 3 个(减去相关配料.名称中包含肉类的菜谱名称)。
I have a SQL question. I'm working with the following set of tables:
https://i.sstatic.net/HzRyl.png
The Recipe table contains 5 recipes, Ingredient contains many ingredients (52), and IngredientList is an associative entity, an implementation of the many-to-many relationship between Recipe and Ingredient. RecipeID and IngredientID are essentially auto-increment ID numbers.
I'm trying to write a query that displays all vegetarian recipes (that is, recipes without
'%beef%',
'%pork%',
'%chicken%',
'%lamb%
in any of their associated Ingredient.Name). The issue I'm running into is that the result set contains one row per ingredient, rather than one row per recipe.
The query that generates this result set is (note that the Ingredient table is named ingredients here):
SELECT recipe.name AS Dish, ingredients.name
FROM (recipe JOIN ingredientlist ON recipe.recipeid=ingredientlist.recipeid
JOIN ingredients ON ingredientlist.ingredientid=ingredients.ingredientid)
WHERE ingredients.name NOT LIKE '%beef%'
AND ingredients.name NOT LIKE '%chicken%'
AND ingredients.name NOT LIKE '%pork%'
AND ingredients.name NOT LIKE '%lamb%';
That query generates 50 results (not 52, because two ingredients are excluded based on their ingredient.name containing the a substring excluded by my WHERE clause).
My goal is to return 3 of the 5 recipe names in the recipe table (subtracting those containing meat in the associated ingredients.name).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能想在成分表中添加 is_vegetarian 标志。
但您的主要问题是您要求数据库通过在 select 子句中包含成分.name 来返回 50 行。如果您只想要食谱,则只需询问食谱:
You might want to add a is_vegetarian flag to your ingredient table.
But you main problem is that you are asking the database to return 50 rows by including ingredients.name in your select clause. If you want only the recipes, you need to ask for only the recipes:
我最终提出了这个问题:
I wound up with this query: