【问题标题】:SQL - Does an object have all the required components?SQL - 对象是否具有所有必需的组件?
【发布时间】:2017-02-10 05:00:33
【问题描述】:

我不太清楚如何表达这个问题才能真正理解我的意思,所以我想下面的例子说明了这个问题。

假设我有一个食谱网站,用户可以在其中注册(数据存储在 Users 表中,用户 ID 是主键)并记录成分(全局成分簿存储在 AllIngredients 表中,成分 ID 是主键密钥)在他们的橱柜中(存储在 UserCabinet 表中的数据,该表链接到用户 ID 和成分 ID)。

然后,假设我有一组食谱(存储在 Recipes 表中,食谱 ID 作为主键)由一组成分组成(存储在 RecipeIngredients 表中,该表链接到食谱 ID和成分 ID)。

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

编辑:以下是创建示例表的 SQL:http://pastebin.com/N9pqmC2r

【问题讨论】:

  • 当然这可以通过 SQL 实现;这就是关系数据库的用途。由于您没有提供任何代码,我们无法告诉您所需查询的确切详细信息。但这就像进行连接查询一样简单。请参阅blog.codinghorror.com/a-visual-explanation-of-sql-joins 了解从哪里开始。
  • 我添加了用于创建表的 SQL。我认为完整的外部连接最接近我想要使用的,但我仍然没有看到如何将它与查找所有食谱联系起来。我可能会看到一次只做一个菜谱,看看完全外连接的结果集的大小是否与该菜谱成分的结果集的大小相匹配,但我不确定我可以从那里去哪里。

标签: mysql sql database


【解决方案1】:
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

【讨论】:

    【解决方案2】:
    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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2016-12-01
      • 2021-09-05
      • 2011-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多