2012-06-16 22 views
3

現在,我在一個ios應用程序中使用sqlite,我希望能夠搜索可以從配料列表製作的食譜(即食譜等這是所提供的成分的子集)sqlite - 找到可以從一組成分製作的食譜

例如:

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 {} 

目前我所成立是

Table Items 
name text primary key 

Table Recipes 
ID required_item integer, recipe_name text 

我可以很容易地包含任意t的食譜做查詢他三種成分和查詢包含所有三種成分的配方,但我一直無法弄清楚如何只

Recipes ∈ P(Ingredients) 

對不起做查詢,我是新來的數據庫編程,和任何幫助將不勝感激

回答

3

您可以使用left join搜索表。然後group by配方。使用having子句要求,對於每個配方,沒有不在搜索列表中的成分。例如:

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.

相關問題