我正在制作一个我可以存储食谱的地方,但我的数据库出了问题。我有3张桌子,食谱,配料和基本成分表。
i = 0*******
j = 0 i = 1*******
j = 0 j = 1 i = 2*******
j = 0 j = 1 j = 2 i = 3*******
j = 0 j = 1 j = 2 j = 3 i = 4*******
j = 0 j = 1 j = 2 j = 3 j = 4 i = 5*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 i = 6*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 i = 7*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 i = 8*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 i = 9*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 i = 10*******
j = 0 j = 1 j = 2 j = 3 j = 4 j = 5 j = 6 j = 7 j = 8 j = 9 j = 10
因此,每当我输入食谱时,我都会被要求提供其中的成分,并检查它是否存在于基础成分表中,如果是这样,它会使用此baseingredient ID并填写成分表中的记录。
我的问题是,在搜索食谱时,我希望能够搜索我冰箱里的食材。因此,如果我输入鸡蛋和面包,它会产生鸡蛋三明治。然而,随着我使用的查询,它将找到所有在其中有鸡蛋的食谱并将其返回,所以例如它会找到蛋糕,煎饼(无论什么包含鸡蛋)。如何限制它以便显示仅包含我作为搜索参数列出的成分的所有配方。
Recipe Table
ID int
name varchar
steps varchar
BaseIngredients Table
ID int
name varchar
Ingredients Table
ID int
baseID int
recipeID int
measurement varchar
答案 0 :(得分:1)
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_1
,ingredient_2
等显然会被您在搜索中输入的内容替换。