如何在单独的实体中将多个列从一个实体连接到单个列?

时间:2016-05-02 08:28:18

标签: mysql sql join

我正在尝试为减肥诊所的客户制作膳食安排数据库。这些是一些食谱:

+-----------+-----------------------+
| recipe_ID | recipe_name           |
+-----------+-----------------------+
|         1 | Healthy Burritos      |
|         2 | Stuffed Peppers       |
|         3 | Breakfast Pizza Slice |
+-----------+-----------------------+

这是一天的计划:

+--------+-----------+-------+--------+
| ddp_ID | breakfast | lunch | dinner |
+--------+-----------+-------+--------+
|      1 |         3 |     1 |      2 |
+--------+-----------+-------+--------+

计划中的早餐,午餐和晚餐中的每个号码都是指代食谱ID的外键。我想执行一个查询,该查询将获取要为用户显示的每个配方的名称。这就是我所得到的,但是我得到了以下错误,我似乎无法解决:ERROR 1066(42000):不唯一的表/别名:' daily_diet_plan&# 39;

SELECT 
recipe.recipe_name 
FROM 
recipe 
INNER JOIN daily_diet_plan ON (daily_diet_plan.breakfast = recipe.recipe_ID)
INNER JOIN daily_diet_plan ON (daily_diet_plan.lunch = recipe.recipe_ID) 
INNER JOIN daily_diet_plan ON (daily_diet_plan.dinner = recipe.recipe_ID);

非常感谢您提供的任何帮助!对此,我真的非常感激。

编辑:这有效!

SELECT recipe.recipe_name 
FROM recipe 
LEFT JOIN daily_diet_plan as brkfast ON (brkfast.breakfast = recipe.recipe_ID) 
LEFT JOIN daily_diet_plan as lunch ON (lunch.lunch = recipe.recipe_ID) 
LEFT JOIN daily_diet_plan as dinner ON (dinner.dinner = recipe.recipe_ID) order by recipe.recipe_name;

1 个答案:

答案 0 :(得分:1)

更新您的查询(我添加了差异别名:

SELECT 
recipe.recipe_name 
FROM 
recipe 
INNER JOIN daily_diet_plan as brkfast ON (brkfast.breakfast = recipe.recipe_ID)
INNER JOIN daily_diet_plan as lunch ON (lunch.lunch = recipe.recipe_ID) 
INNER JOIN daily_diet_plan as dinner ON (dinner.dinner = recipe.recipe_ID);