MySQL多对多关系匹配

时间:2011-07-07 22:06:32

标签: mysql join relational-database associative-table

我正在制作一个鸡尾酒数据库,现在我有三张桌子:

  • 饮料有专栏drink_id和drink_name
  • 成分具有列成分_id和成分名称
  • 第三个是名为recipes的简单关系表,其中包含drinks_id和ingredients_id

我想用一组ingredient_ids查询数据库,并从这组成分中获取一组饮料。例如,如果饮料A含有成分(1,2),饮料B含有(1,3),饮料C含有(1,2,3),输入成分1,2和3应该返回饮料A,B和C我刚开始用MySQL教自己数据库设计,非常感谢任何帮助。对不起,如果在其他地方已经回答了这个问题,我试过但不太知道如何搜索它。

3 个答案:

答案 0 :(得分:2)

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 :(得分:1)

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
  [...]

绑定?并为集合中的每个成分添加exists

答案 2 :(得分:0)

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}