理解多个连接的问题

时间:2018-01-12 18:59:47

标签: sql postgresql rails-postgresql

我有以下表格:

users
 ____________
| id         |
| first_name |
|____________|

pre_task_plans
 ____________
| id         |
| creator_id | (fk user_id)
|____________|

pre_task_plan_users
 __________________
| id               |
| user_id          |
| pre_task_plan_id |
|__________________|

我正在尝试让所有用户获得pre_task_plans,我是(users.id 1)的创建者

我有

SELECT users.*
FROM users
JOIN pre_task_plans as ptp on ptp.creator_id = 1
JOIN pre_task_plan_users as ptpu on ptpu.pre_task_plan_id = ptp.id

但它返回的用户不在与pre_task_plans相关的pre_task_plan_users中。我不了解第二次JOIN是如何工作的?

PSQL 9.6.2

1 个答案:

答案 0 :(得分:2)

SELECT users.*, other.*
FROM users
JOIN pre_task_plans as ptp on ptp.creator_id = users.id
JOIN pre_task_plan_users as ptpu on ptpu.pre_task_plan_id = ptp.id
join users as other on pre_task_plan_users.user_id = other.id
where users.id = 1

您将每个pre_task_plan加入其创建的user,然后将结果缩小为您的用户(仅限您创建的那些)。

您也应该显示pre_task_plans中的一些行,这样您只能看到自己的idfirst_name