3

我正在制作鸡尾酒数据库,现在我有三个表:

  • 饮料有列drinks_id 和drinks_name
  • 成分具有列成分_id 和成分_名称
  • 第三个是一个名为recipes 的简单关系表,其中包含drinks_id 和components_id

我想使用一组成分 ID 查询数据库,并从该组成分中获取一组可用的饮料。例如,如果饮料 A 包含成分 (1,2),饮料 B 包含 (1,3),饮料 C 包含 (1,2,3),则输入成分 1,2 和 3 应返回饮料 A、B 和 C . 我刚开始用 MySQL 自学数据库设计,非常感谢任何帮助。抱歉,如果这已在其他地方得到解答,我试过但不太知道如何搜索它。

4

3 回答 3

3

尝试

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)
于 2011-07-07T22:15:56.850 回答
2
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

于 2011-07-07T22:10:57.940 回答
-1
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}
于 2011-07-07T22:12:52.013 回答