所以我有一个看起来有点像这样的模式:
table recipes (int id)
table ingridients (int id)
table recipe_ingridients(recipe_id, ingridient_id)
如果存在一个由一组特定成分组成的配方,最好的方法是什么?
类似这样的东西(伪代码(:
SELECT recipe WHERE ingridient_id`s = [3, 5, 7]
对于这种用途,它是不是设计得很糟糕?如果是这样,还有更好的方法吗?
如果集合的所有成员都必须存在
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
编辑注意,它还返回包含所需集合超集的配方。如果需要完全匹配
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
数据模型,看起来合理,可以使用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
)