SQL连接多个表

时间:2015-01-28 21:46:34

标签: mysql join

通过这样的声明,我可以获得食谱名称以及数量 他们每个人都有的成分。

SELECT
r.name, COUNT(i.id) as num_ingredients
FROM recipes AS r
    LEFT JOIN recipe_ingredients ON r.id = recipe_ingredients.recipe_id
    LEFT JOIN ingredients AS i ON recipe_ingredients.ingredient_id = i.id
GROUP BY r.id

如何将chefs.name添加到我的SELECT以及我已有的数据?

table schema

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT
r.name, COUNT(i.id) as num_ingredients, che.name AS chefs_name
FROM recipes AS r
    LEFT JOIN recipe_ingredients ON r.id = recipe_ingredients.recipe_id
    LEFT JOIN ingredients AS i ON recipe_ingredients.ingredient_id = i.id
    LEFT JOIN chefs AS che ON r.chef_id = che.id
GROUP BY r.id

如果我理解,你也想加入厨师表并选择它的名字。

您必须在SELECT语句中对其进行别名,因为您选择了2个具有相同名称的列。

我还认为,recipes.chef_id列的数据类型应与chefs.id(int(11)或int(255))相同。