我的数据库中有以下 3 个表,但在查询它们以获得我想要的结果时遇到一些问题。我正在尝试按成分搜索食谱。
SQL fiddle :Fiddle
这是我的表格: 成分
+---------------+---------+
| ingredient_id | name |
+---------------+---------+
| 1 | tomato |
| 2 | onion |
| 3 | rice |
| 4 | chicken |
| 5 | beef |
| 6 | noodles |
| 7 | salt |
+---------------+---------+
食谱
+-----------+------------------+
| recipe_id | name |
+-----------+------------------+
| 1 | tomato goodness |
| 2 | meat deluxe |
| 3 | chicken surprise |
+-----------+------------------+
成分索引
+-----------+---------------+
| recipe_id | ingredient_id |
+-----------+---------------+
| 1 | 1 |
| 1 | 5 |
| 1 | 7 |
| 2 | 5 |
| 2 | 6 |
| 2 | 7 |
| 3 | 4 |
| 3 | 3 |
| 3 | 7 |
+-----------+---------------+
我想要实现的目标是过滤我可以使用指定成分制作的所有食谱。问题来了:
此查询:
select DISTINCT r.name
from
recipes r
inner join ingredient_index i
on i.recipe_id = r.recipe_id
where i.ingredient_id IN (2, 7, 5);
给了我错误的结果,因为我没有足够的原料来制作任何食谱,但我仍然得到了我可以制作所有食谱的结果。发生这种情况是因为 recipe_id 在 Ingredient_Index 表中重复。
任何帮助我都会非常感激。
最佳答案
正如 jarlh 所说,检查是否缺少任何成分:
select DISTINCT r.name
from recipes r
where not exists (
select 1 from ingredient_index i where r.recipe_id=i.recipe_id and i.ingredient_id not in (2,5,7)
)
关于mysql - 食谱数据库,按成分搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47453267/