MySQL many to many relationship matching

546 Views Asked by At

I'm making a cocktail database, and right now I have three tables:

  • drinks has columns drinks_id and drinks_name
  • ingredients has columns ingredients_id and ingredients_name
  • The third is a simple relationship table called recipes that has drinks_id and ingredients_id

I want to query the database with a set of ingredient_ids and get the set of drinks available from that set of ingredients. For example, if drink A contains ingredients (1,2), drink B contains (1,3), and drink C contains (1,2,3), inputting ingredients 1,2 and 3 should return drinks A, B and C. I just started teaching myself database design with MySQL and any help is much appreciated. Sorry if this has been answered elsewhere, I tried but didn't quite know how to search for it.

3

There are 3 best solutions below

1
On BEST ANSWER

TRY

SELECT d.drink_name
FROM tbl_drink d
INNER JOIN tbl_receipe r ON r.drink_id=d.drink_id
INNER JOIN tbl_ingredient i ON i.ingredient_id = r.ingredient_id
WHERE `given ID` IN (i.ingredient_id)
1
On
select * from drink d where
  exists (select * from recipe where drink_id = d.drink_id and ingred_id = ?) and
  exists (select * from recipe where drink_id = d.drink_id and ingred_id = ?) and
  [...]

Bind ?'s and add an exists for each ingredient in the set.

4
On
SELECT d.drinks_name
FROM drinks d
JOIN recipes AS r ON (r.drinks_id = d.drinks_id)
JOIN ingredients AS i1 ON (i1.ingredients_id = r.ingredients_id)
JOIN ingredients AS i2 ON (i2.ingredients_id = r.ingredients_id)
...
JOIN ingredients AS iN ON (iN.ingredients_id = r.ingredients_id)
WHERE
    i1.ingredients_name = ${first_ingredient}
    i2.ingredients_name = ${second_ingredient}
    ...
    iN.ingredients_name = ${Nth_ingredient}