Reputation: 11737
An SQL question about subsets,
Consider a database design of a recipe table, ingredient table and a recipe_ingredient joining table. We will only need the joining table for this problem.
recipe_ingredient table:
Column | Type | Modifiers
--------+---------+-----------
r_id | integer | # Key to the recipe table
i_id | integer | # Key to the ingredient table
A recipe requires 1 or more ingredients. Given a list of ingredient ids is it possible to find all compatible recipes? A compatible recipe would have a subset of the supplied ingredients.
This query is close. It allows me to see all the ingredient ids required by each recipe.
select array_agg(i_id), r_id from recipe_ingredient group by r_id
I could run the above query and then compare the ingredient list with my own list in code. But I would like to know if everything can be done at the SQL level,
What I would like to do is this:
select array_agg(i_id), r_id from recipe_ingredient group by r_id
HAVING array_agg(i_id) IS_SUBSET_OF (:INGREDIENT_LIST)
Is something like this possible?
Upvotes: 1
Views: 759
Reputation: 1269873
Assuming you have a recipes table:
select r.*
from recipes r
where not exists (select 1
from recipe_ingredient ri
where ri.r_id = r.id and
ri.i_id not in ( . . . )
);
This gets all recipes that have no ingredients outside your list.
Upvotes: 1
Reputation: 1444
Put your ingredient list to a temp table variable:
DECLARE @selectedIngredientList TABLE (id INT);
SELECT DISTINCT r_id
FROM recipe_ingredient ri INNER JOIN @selectedIngredientList i
ON ri.i_id = i.id
Upvotes: -1