最佳搜索某些排列时如何查询多对多?

How to query a many-to-many when searching for certain permutation optimally?

所以我有一个看起来有点像这样的架构:

table recipes (int id)
table ingridients (int id)

table recipe_ingridients(recipe_id, ingridient_id)

查找是否存在包含一组特定成分的食谱的最佳方法是什么?

类似这样的东西(伪代码):

SELECT recipe WHERE ingridient_id`s = [3, 5, 7]

这种用途的架构设计不佳吗?如果是这样,是否有更好的方法来解决这个问题?

数据模型,似乎合理,你可以使用exists in:

select * from recipes r
where exists (select 1 from recipe_ingridients ri
              where ri.ingridient_id in ( 3,5,7)
               and ri.recipe_id = r.id
              )

如果集合中的所有成员都必须存在

select * 
from recipes r
where (select count(*) * 
              from recipe_ingridients ri
              where ri.ingridient_id in (3,5,7)
              and ri.recipe_id = r.id
              ) = 3

编辑 还要注意 returns 包含所需集超集的食谱。如果需要精确匹配

select * 
from recipes r
where (select count(*) - count(case when ri.ingridient_id in (3,5,7) then 1 end) 
              from recipe_ingridients ri
              where  ri.recipe_id = r.id
              ) = 0