1

this is my scenario: I have a table that holds recipes, and another that holds ingredients linked to a recipe (recipe_ingredients).

TABLE RECIPE_INGREDIENTS:

ID      RECIPE_ID     INGREDIENT_ID
1           1              6
2           2              3
3           2              4

in my case, I want to return all recipes with some ingredients introduced by user (could be one or more), in this example let's say all recipes with ingredients 3 and 4. Obviusly when I only query for one ingredient there's no problem, but I don't know how achieve that with more than one... Thanks all in advance! any advice is welcome!

2 Answers 2

4

It sounds like you want this:

select RECIPE_ID
from RECIPE_INGREDIENTS
where INGREDIENT_ID in (3, 4)
group by RECIPE_ID
having count(distinct INGREDIENT_ID ) >=2

See SQL Fiddle with Demo

Then if you want to join this to you recipe table:

select r.*
from recipes r
inner join
(
  select RECIPE_ID
  from RECIPE_INGREDIENTS
  where INGREDIENT_ID in (3, 4)
  group by RECIPE_ID
  having count(distinct INGREDIENT_ID ) >=2
) ri
  on r.RECIPE_ID = ri.RECIPE_ID
Sign up to request clarification or add additional context in comments.

Comments

3

Assuming you have 3 tables recipes , ingradients and recipe_ingrediants

SELECT 
    r.*,
    GROUP_CONCAT(i.ingradients)
FROM recipes as r
LEFT JOIN recipe_ingrediants as ri ON ri.recipe_id = r.id
LEFT JOIN ingrediants as i ON r.id = ri.ingrediant_id
GROUP BY r.id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.