仅在所有成分匹配的情况下获取食谱

时间:2018-11-28 21:57:30

标签: sql database

我有桌子:

create table recipe(
recipe_id int IDENTITY(1,1) primary key,
recipe_name varchar(100),
decription text);

create table ingredient(
ingredient_id int IDENTITY(1,1) primary key,
ingredient_name varchar(100))

create table recipe_i(
id_h int identity(1,1) primary key,
rec_id int foreign key references recipe(recipe_id),
ing_id int foreign key references ingredient(ingredient_id))

我从用户那里获得了各种配料,例如(“牛奶”,“面粉”,“盐”,“蛋”,...) 我只想在所有这些成分都在食谱中的情况下退回食谱。

我尝试过:

select recipe_name
from recipe
where recipe_id  =
    ( select distinct rec_id
        from recipe_i 
       where ing_id =all
              ( select ingredient_id
                  from ingredient
                  where ingredient_name in ('flour','egg','oil','salt','milk')
              )
    );

,但结果为空。

1 个答案:

答案 0 :(得分:0)

您可以匹配计数。这是一种方式。它会匹配使用给定成分可以制作的所有食谱,但是您可能还剩下一些成分。例如,这将只匹配面粉和牛奶的配方,而不匹配面粉和酵母的配方,因为未指定酵母。

select recipe_name
from recipe r
where 
  -- Where total number of ingredients ...
  ( select count(*) from recipe_i ri 
    where ri.rec_id = r.recipe_id) 
    = -- equals
  -- specified ingredients
  ( select count(*) 
    from recipe_i ri 
    inner join ingredient i on i.ingredient_id = ri.ing_id
    where 
      ri.rec_id = r.recipe_id and
      i.ingredient_name in ('flour','egg','oil','salt','milk'));

但是再读一遍,我想您反过来想要它,只返回包含 all 成分的食谱。以下查询会执行此操作,但还会返回包含这些成分及更多的食谱。

select recipe_name
from recipe r
where 
  -- Total number of ingredients
  ( select count(*) 
    from ingredient i
    where 
      i.ingredient_name in ('flour','egg','oil','salt','milk'))
    = -- equals
  -- number of matching ingredients in the recipe
  ( select count(*) 
    from recipe_i ri 
    inner join ingredient i on i.ingredient_id = ri.ing_id
    where 
      ri.rec_id = r.recipe_id and
      i.ingredient_name in ('flour','egg','oil','salt','milk'));

如果愿意,您可以在一个查询中组合两个条件(带有and),以获得与给定成分完全匹配的食谱。