gpt4 book ai didi

mysql - 查询返回两个表的并集

转载 作者:行者123 更新时间:2023-11-29 09:35:58 26 4
gpt4 key购买 nike

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

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))

配方结构

enter image description here

<小时/>

user_plan结构
enter image description here
根据我的预期和表中可用的数据,它应该返回 2 行,但它返回 10 行。请帮我解决这个问题。谢谢。我在 ubuntu 上使用 mysql 服务器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

这是一种非常古老的连接表样式,有必要在 WHERE 子句中提供关系作为条件,如

WHERE recipe.recipe_id = user_plan.recipe_id 

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

您最好在 FROM 子句中说明您使用的联接类型。这里INNER JOIN 是合适的。然后,您可以在 INNER JOIN 后面的 ON 子句中提供表的关系:

FROM Recipe INNER JOIN user_plan ON Recipe.recipe_id = user_plan.recipe_id 

现在很清楚哪些表正在被连接,更重要的是,它们是如何连接的。从那里开始,您的其余条件可以卡在 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;

关于mysql - 查询返回两个表的并集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57579811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com