简体   繁体   中英

sql subset query

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM