MySQL查询配方,所有可用的令人失望

时间:2015-10-21 22:42:26

标签: mysql

假设我有4个MySQL表:

recipe: id, name
incredient: id, name
recipe_incredient: id, recipe_id, incredient_id
available: id, incredient_id

我想要一个查询,它返回所有食谱+令人难以置信的令人难以置信的。

示例:

我有吐司(=面包+火腿)和汤(=火腿+鸡肉)。 我有面包和火腿。 因此我想要Toast,但没有Soup。

recipes:
1, Toast
2, Soup

incredients:
1, bread
2, ham
3, chicken

recipe_incredient:
1, 1, 1
2, 1, 2
3, 2, 2
3, 2, 3

available:
1, 1
2, 2


Result should be:
Toast, bread
Toast, ham

1 个答案:

答案 0 :(得分:0)

排除部分是 double NOT EXISTS子句:查找“不存在”的配方“不可用”。

SQL Fiddle

select r.name as recipe, i.name as incredient
  from recipe r
  join recipe_incredient ri on ri.recipe_id = r.id
  join incredient i on i.id = ri.incredient_id
 where not exists (
          select *
            from recipe_incredient ri2
           where ri2.recipe_id = r.id
             and not exists (
                    select *
                      from available a
                     where a.incredient_id = ri2.incredient_id
                 )
       )

也可以使用NOT IN完成。

select r.name as recipe, i.name as incredient
  from recipe r
  join recipe_incredient ri on ri.recipe_id = r.id
  join incredient i on i.id = ri.incredient_id
 where r.id not in (
          select ri2.recipe_id
            from recipe_incredient ri2
           where ri2.incredient_id not in (
                    select a.incredient_id
                      from available a
                 )
       )

最好的取决于可用的索引,SQL Optimizer和您的个人偏好。