我不太确定如何表达这个问题以便真正理解我的意思,所以我想下面的例子说明了这个问题。
假设我有一个食谱网站供用户注册(存储在用户表中的数据,用户ID是主键)并记录成分(存储在AllIngredients表中的全球成分簿,含有成分)它们在机柜中具有ID(主键)(存储在UserCabinet表中的数据,链接到用户ID和成分ID)。
然后,让我们说我有一组食谱(存储在食谱表中,配方ID是主键),它们由一组成分组成(存储在RecipeIngredients表中,食谱ID和成分ID的链接。)
在这种情况下,我问的问题是如何确定用户拥有所有成分的配方?它们可能含有比配方要求更多的成分,这很好,但它们可以少用(即它们不会丢失任何成分)。这只能用SQL实现,还是需要使用编程语言进行多次查询/操作?
编辑:以下是用于创建示例表的SQL,我在谈论:http://pastebin.com/N9pqmC2r
答案 0 :(得分: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
)
答案 1 :(得分: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