我不太确定如何表达这个问题才能真正理解我的意思,所以我想下面的例子可以说明这个问题。
假设我有一个食谱网站,用户可以在其中注册(数据存储在 Users 表中,用户 ID 是主键)和记录成分(全局成分书存储在 AllIngredients 表中,成分 ID 是主键) key ),他们在他们的柜子里(数据存储在 UserCabinet 表中,链接到用户 ID 和成分 ID)。
然后,假设我有一组食谱(存储在 Recipes 表中,食谱 ID 是主键),这些食谱由一组成分组成(存储在 RecipeIngredients 表中,链接到食谱 ID和成分 ID)。
在这种情况下,我要问的问题是如何确定用户拥有哪些食谱的所有配料?他们的配料可能比食谱要求的多,这很好,但他们不能少(即他们不能缺少任何东西)。仅使用 SQL 是否可行,还是需要使用编程语言进行多次查询/操作?
编辑: 以下是创建我正在谈论的示例表的 SQL:http://pastebin.com/N9pqmC2r
最佳答案
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
关于mysql - SQL - 对象是否具有所有必需的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42151835/