简体   繁体   English

SQL查询可从成分集合中制成的配方

[英]SQL query for recipes that can be made from collection of ingredients

I have a database that has a table of Ingredients I and a table of Recipes R. The two tables have a many-to-many relationship, as one recipes uses many ingredients and one ingredient is used in many recipes. 我有一个数据库,其中有一个成分表I和一个配方R表。这两个表具有多对多关系,因为一种配方使用了很多成分,而一种成分则用在了很多配方中。 I have a third cross-reference table that uses the cross-reference validation pattern to enforce my many-to-many relationship, and is done using string foreign keys (instead of integers). 我有第三个交叉引用表,该表使用交叉引用验证模式来加强我的多对多关系,并使用字符串外键(而不是整数)完成。

Assuming I have a collection of ingredients C outside of my database, how can I query Recipe table R for every recipe that can be made using ONLY the list of ingredients supplied in C? 假设我的数据库外有成分C的集合,如何仅使用C中提供的成分列表就每个配方可以查询配方表R?

Other things to consider 其他要考虑的事情

1) Speed will (of course) be a concern eventually, but correctness is what I'm stuck on at the moment. 1)(当然)速度最终会成为一个问题,但是正确性是我目前坚持的。

2) The collection of ingredients C might be very large (~100 ingredients). 2)成分C的集合可能很大(约100种成分)。

Any answers or even just pointers in the right direction would be greatly appreciated. 任何答案,甚至只是正确方向的指针,将不胜感激。

Thanks, 谢谢,

Alec 亚历克

One way is to write: 一种方法是编写:

select ...
  from R
 where ID not in
        ( select R_ID
            from RI
           where I_ID not in
                  ( select I_ID
                      from C
                  )
        )
;

That is: start with C . 那就是:从C开始。 Select all recipe–ingredient cross-references where the ingredient is not in C . 选择成分不在 C所有配方成分参考。 This gives you the set of all recipes that cannot be made using only ingredients in C . 这为您提供了仅使用C成分无法制作的所有配方集。 Then, select all recipes that aren't in that set. 然后,选择不在该组中的所有食谱。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM