To display ONLY REVENUES that have ALL ingredients, it would be as follows:
Simplified form (I think, 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
HAVING COUNT
is required because in this part WHERE ig.cod_ingrediente IN (1,6)
, you are selecting ANY RECIPE that has at least ONE 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 out recipes by ingredients, and then see which one is in all selects.
For the time being, you will have to loop by ingredient, and add in the recipes select check.
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?