gpt4 book ai didi

mysql - 配方数据库,按成分搜索

转载 作者:搜寻专家 更新时间:2023-10-30 20:24:03 24 4
gpt4 key购买 nike

我的数据库中有以下 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_idIngredient_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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com