mysql - SQL multi-table composite key unique query -


for starters, background information. building simple recipe book database , i'm trying build query show me can make based on items in pantry. table schemas follows:

recipe(*recipeid*, recipename) recipe_ingredient(***recipeid***, **ingredientid**) ingredient(*ingredientid*, ingredientname) pantry_item(*itemid*, itemname) 

the fields in recipe_ingredient table make composite key , both foreign keys recipe(recipeid) , ingredient(ingredientid) table. i'm using following test data:

recipe table recipeid,recipename 1,'food 1' 2,'food 2'  ingredient table ingredientid, ingredientname 1,'ing 1' 2,'ing 2' 3,'ing 3'  recipe_ingredient table recipeid,ingredientid 1,1 1,2 2,2 2,3  pantry_item table itemid,itemname 1,'ing 2' 2,'ing 3' 

so i'm trying query list of recipenames based on items have in pantry. this, mean must have ingredients recipe in pantry added list. therefore ideal query based on test data result in 'food 2'. problem i'm running enforcing 'all ingredients' recipe part.

i've tried few different queries , result in every recipe being returned.

select recipename recipe recipeid in (select recipeid recipe_ingredient ingredientid in (select ingredientid ingredient ingredientname in (select itemname pantry_item))) 

does have ideas how can accomplish this? there possible query this, or have restructure database?

first off if can put only ingredients pantry pantry schema should rather this

create table pantry (   ingredientid int,   foreign key (ingredientid) references ingredient (ingredientid) ); 

now, can leverage having clause desired result

select recipename   (   select recipeid     recipe_ingredient ri left join pantry p       on ri.ingredientid = p.ingredientid    group recipeid    having count(*) = count(p.ingredientid) ) q join recipe r     on q.recipeid = r.recipeid 

output:

 | recipename | |------------| |     food 2 | 

here sqlfiddle demo


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -