2017-02-10 54 views
1

我不太确定如何解释这个问题以真正理解我的意思,所以我想下面的例子说明了这个问题。SQL - 对象是否具有所有必需的组件?

比方说,我有一个配方网站,用户可以注册(存储在用户表中的数据,用户ID是主键)和记录成分(存储在AllIngredients表中的全球成分簿,成分ID是主数据库)(数据存储在UserCabinet表中,链接到用户ID和成分ID)。

然后,假设我有一组食谱(存储在食谱表中,食谱ID是主关键字),这些食谱由一组成分组成(存储在RecipeIngredients表中,链接到食谱ID和成分ID)。

在这种情况下,我所问的问题是如何确定用户拥有所有配料的食谱?他们可能有比配方要求更多的成分,这很好,但它们不能少(即不能缺少任何)。这是仅仅使用SQL的可能性,还是需要使用编程语言进行多次查询/操作?

编辑:下面是创建我谈论的样本表的SQL:http://pastebin.com/N9pqmC2r

+0

当然这可能与SQL有关;这就是关系数据库的作用。由于您没有提供任何代码,因此我们无法告诉您所需查询的确切详细信息。但是,它与执行联合查询一样简单。请参阅https://blog.codinghorror.com/a-visual-explanation-of-sql-joins/以了解从何处着手。 – Sablefoste

+0

我添加了我将用来创建表的SQL。我认为完整的外部联接最接近我想要使用的内容,但我仍然没有看到如何配合找到所有的配方。我也许可以看到每次只做一个配方,看看完整外连接的结果集的大小是否与该配方成分的结果集的大小相匹配,但我不确定我可以从哪里出发。 –

回答

0
select r.* 
from recipes r 
join recipeComponents rc on rc.recipe_id = r.id 
join userCabinet uc on uc.ingredient_id = rc.ingredient_id 
where uc.user_id = ? 
group by r.id 
having count(uc.ingredient_id) = (
    select count(*) 
    from recipeComponents rc1 
    where rc1.recipe_id = r.id 
) 

或者

select distinct r.* 
from recipes r 
join recipeComponents rc on rc.recipe_id = r.id 
join userCabinet uc on uc.ingredient_id = rc.ingredient_id 
where uc.user_id = ? 
    and not exists (
    select * 
    from recipeComponents rc1 
    where rc1.recipe_id = r.id 
     and not exists (
      select * 
      from userCabinet uc1 
      where uc1.ingredient_id = rc1.ingredient_id 
    ) 
) 

或者

select r.* 
from recipes r 
left join (
    select rc.recipe_id 
    from recipeComponents rc 
    left join userCabinet uc 
     on uc.user_id = ? 
     and uc.ingredient_id = rc.ingredient_id 
    where uc.ingredient_id is null 
) u on u.recipe_id = r.id 
where u.recipe_id is null 
0
select distinct u.user_id, r.recipe_id 
from recipeComponents r 
left join userCabinet u on r.ingredient_id = u.ingredient_id 
where recipe_id not in (
    select recipe_id 
    from recipeComponents r 
    left join userCabinet u on r.ingredient_id = u.ingredient_id 
    where u.user_id is null 
) 
相关问题