查询返回两个表的联合

Query returning Union of two tables

我正在尝试使用多列子查询从 table 中检索数据,但它合并了两个 table 的结果。我无法修改它以获得实际结果。 这是我的查询

select id from  Recipe,user_plan where Recipe.id in (select meal_number from user_plan where week_id=(select max(week_id) from user_plan where user_id=:user_id))

配方结构


user_plan结构

根据我的预期和 table 中可用的数据,它应该 return 2 行,但它是 returning 10 rows.Please 帮助我解决这个问题。谢谢。 我在 ubuntu 上使用 mysql-server user_plan

的样本数据
+---------+---------+-------------+-----------+
| user_id | week_id | meal_number | recipe_id |
+---------+---------+-------------+-----------+
|       1 |       1 |           1 |         1 |
|       1 |       1 |           3 |         1 |
|       2 |       2 |           2 |         2 |
|       2 |       4 |           2 |         2 |
|       3 |       3 |           3 |         3 |
+---------+---------+-------------+-----------+

预期输出

+----+
| id |
+----+
|  1 |
|  3 |
+----+

实际输出

+----+
 | id |
 +----+
 |  1 |
 |  3 |
 |  1 |
 |  3 |
 |  1 |
 |  3 |
 |  1 |
 |  3 |
 |  1 |
 |  3 |
 +----+

您正在做:

FROM Recipe, user_plan

这是一种非常古老的加入 table 的方式,有必要在 WHERE 子句中提供关系作为条件,例如

WHERE recipe.recipe_id = user_plan.recipe_id 

如果不这样做,将导致 Recipe 中的每条记录都与 user_plan 中的每条记录相连接,这几乎总是不可取的。

您最好在 FROM 子句中说明您使用的连接类型。这里 INNER JOIN 是合适的。然后在 INNER JOIN:

之后的 ON 子句中提供 table 的关系
FROM Recipe INNER JOIN user_plan ON Recipe.recipe_id = user_plan.recipe_id 

现在很清楚哪些 table 正在加入,更重要的是,它们是如何加入的。从那里您的其余条件可以挂在 WHERE 子句中:

 SELECT * 
 FROM Recipe INNER JOIN user_plan ON Recipe.recipe_id = user_plan.recipe_id 
 WHERE user_plan.week_id=(select max(week_id) from user_plan where user_id=:user_id) 
     and user_plan.user_id = :user_id;