gpt4 book ai didi

mysql - 从数据透视表中检索与所有结果匹配的记录

转载 作者:行者123 更新时间:2023-11-29 10:41:33 24 4
gpt4 key购买 nike

我正在创建一个可以存储我制作的食谱的地方,但我的数据库遇到了问题。我有 3 张 table 、一张食谱、一张配料表和一张基本配料表。

Recipe Table
ID int
name varchar
steps varchar

BaseIngredients Table
ID int
name varchar

Ingredients Table
ID int
baseID int
recipeID int
measurement varchar

因此,每次我输入食谱时,都会询问其中的成分,并检查它是否存在于基本成分表中,如果存在,则使用此基本成分 ID 并填写成分表中的记录。

我的问题是,在搜索食谱时,我希望能够搜索冰箱里的食材。因此,如果我输入“鸡蛋和面包”,它会生成一个鸡蛋三明治。然而,通过我使用的查询,它将找到所有含有鸡蛋的食谱并将其返回,例如它会找到蛋糕、煎饼(无论真正含有鸡蛋的东西)。我如何限制它,以便它显示仅包含我作为搜索参数列出的成分的所有食谱。

select recipes.id, recipes.name from recipes inner join ingredients on recipes.id = ingredients.recipeID inner join baseingredient on ingredients.baseID = baseingredient.id where  baseingredient.name = 'Eggs' 

最佳答案

select r.id
,r.name
from recipes r
where exists (select *
from ingredients i1
inner join baseIngredients b1
on i1.id=b1.baseId
where i1.recipeID = r.id
and b1.name = 'ingredient_1'
)
...
and exists (select *
from ingredients iN
inner join baseIngredients bN
on iN.id=bN.baseId
where iN.recipeID = r.id
and bN.name = 'ingredient_N'
)

编辑:以上查询将返回其成分列表包括您指定的所有食谱。如果我误解了你的问题,而你想要的实际上只是除了你指定的成分之外不使用其他成分的食谱,请尝试以下操作:

select r.id
,r.name
from recipes r
where not exists (select *
from ingredients i
inner join baseIngredients b
on i.id=b.baseId
where i.recipeID = r.id
and b.name not in ('ingredient_1', 'ingredient_2', ..., 'ingredient_N')

其中 ingredient_1ingredient_2 等显然应该替换为您在搜索中输入的内容。

关于mysql - 从数据透视表中检索与所有结果匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45373855/

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