To display ONLY THE REVENUES who have ALL the ingredients, would be such forms:
Simplified form (I believe, easier):
SELECT re.cod_receita, COUNT(ig.cod_ingrediente)
FROM receitas re
LEFT JOIN ingredientes_receitas ir ON ir.cod_receita = re.cod_receita
LEFT JOIN ingredientes ig ON ig.cod_ingrediente = ir.cod_ingrediente
WHERE ig.cod_ingrediente IN (1,6)
GROUP BY re.cod_receita
HAVING COUNT(ig.cod_ingrediente) = 2
You will pass the ingredients on:
WHERE ig.cod_ingrediente IN (1,6)
And the total amount of ingredients (in this case above are 2) in:
HAVING COUNT(ig.cod_ingrediente) = 2
The HAVING COUNT
it is necessary, therefore in this part WHERE ig.cod_ingrediente IN (1,6)
, you are selecting ANY RECIPE who has at least ONE OF ingredients contained in (1,6)
.
Sqlfiddle
With sub-querys:
SELECT *
FROM receitas
WHERE cod_receita IN
(
SELECT re.cod_receita
FROM receitas re
LEFT JOIN ingredientes_receitas ir ON ir.cod_receita = re.cod_receita
LEFT JOIN ingredientes ig ON ig.cod_ingrediente = ir.cod_ingrediente
WHERE ig.cod_ingrediente = 1
)
AND cod_receita IN
(
SELECT re.cod_receita
FROM receitas re
LEFT JOIN ingredientes_receitas ir ON ir.cod_receita = re.cod_receita
LEFT JOIN ingredientes ig ON ig.cod_ingrediente = ir.cod_ingrediente
WHERE ig.cod_ingrediente = 6
)
You would have to filter recipes by ingredients, and then see which one is in all selects.
For now, you will have to loop by ingredient, and add in the select check of the recipes.
In the rush I remembered these forms... later I will see if it has simpler forms, thinking of generating in PHP.
Extra links to JOINS
:
Difference between INNER JOIN, JOIN and WHERE?
What is the difference between LIKE, IN and BETWEEN in Mysql?
You want the answer in Mysql, or a solution?
– Sveen
Basically you need to make a
join
between tables filtering in ingredients_recipes the ingredients and quantity to ensure that all are included– Ricardo Pontual
@Sveen actually I am accepting both. If it is the solution, I just need to understand correctly so that I can implement in My.
– Marcos Tesolin