sqlite - find recipes that can be made from a set of ingredients

为君一笑 提交于 2021-02-18 17:07:33

问题


Right now I am using sqlite within a ios application, and I want to be able to search for recipes that can be made from a list of ingredients (ie recipes such that are a subset of the provided ingredients)

For example:

Recipe 1: A B C
Recipe 2: A B
Recipe 3: C D
Recipe 4: A
Recipe 5: E

Query for ingredients A B C returns recipes {1, 2, 4}
Query for ingredients A B returns recipes {2, 4}
Query for ingredients D returns {}

Currently what I have set up is

Table Items
name text primary key

Table Recipes
ID required_item integer, recipe_name text

I can easily do queries for recipes containing any of the three ingredients and queries for recipes containing all of the three ingredients, but I haven't been able to figure out how to do queries for only

Recipes ∈ P(Ingredients)

Sorry, I'm new to database programming, and any help would be greatly appreciated


回答1:


You could use a left join to a search table. Then group by recipe. Use a having clause to demand that for each recipe, there are no ingredients that are not in the search list. For example:

select  ri.RecipeNr
from    RecipeIngredients ri
left join
        (
        select  'A' as Ingredient
        union all
        select  'B'
        union all
        select  'C'
        ) search
on      ri.Ingredient = search.Ingredient
group by
        ri.RecipeNr
having  count(case when search.Ingredient is null then 1 end) = 0

Live example at SQL Fiddle.



来源:https://stackoverflow.com/questions/11066631/sqlite-find-recipes-that-can-be-made-from-a-set-of-ingredients

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!