简体   繁体   English

在PostgreSQL中用多个表编写JOIN查询

[英]Writing JOIN queries in PostgreSQL with multiple tables

I've got 3 tables that look vaguely like this: 我有3张桌子,看起来像这样:

Users
----------
UserID
Name
Phone

User Groups
-----------
GroupID
GroupActivity

Group Membership
---------------
UserID
GroupID

I am trying to print the user name and phone number for all the groups with members undertaking a certain activity. 我正在尝试打印所有成员进行特定活动的组的用户名和电话号码。 For example, group 1 activity = knitting, group 2 activity = sewing and group 3 activity = knitting. 例如,第1组活动=针织,第2组活动=缝纫,第3组活动=针织。 I want to select all the members that are knitting but I am unsure how to join the three tables in one query. 我想选择所有要编织的成员,但不确定如何在一个查询中联接三个表。 This is what I tried so far: 这是我到目前为止尝试过的:

SELECT                                                                   
users.name, users.phone, groups.activity  
FROM users
INNER JOIN group_membership ON group_membership.userID = users.userID 
WHERE groups.activity = 'Knitting';

This ends up throwing the following error: 最终会引发以下错误:

ERROR: missing FROM-clause entry for table "groups" 错误:缺少表“组”的FROM子句条目

To fix this I tried adding teams to the FROM clause like so: 为了解决这个问题,我尝试将teams添加到FROM子句中,如下所示:

FROM users,groups

However, this in turn gives me this error: 但是,这反过来给了我这个错误:

ERROR: invalid reference to FROM-clause entry for table "members" 错误:对表“成员”的FROM子句条目的引用无效

Any help here would be appreciated. 在这里的任何帮助,将不胜感激。

Try This 尝试这个

SELECT                                                                   
users.name, users.phone, user_groups.activity  
FROM users 
INNER JOIN group_membership ON group_membership.userID = users.userID 
inner join user_groups on user_groups.groupid = group_membership.groupid
WHERE user_groups.activity = 'Knitting';

You can have that shorter with table aliases and the USING clause: 您可以使用表别名和USING子句来缩短它:

SELECT ug.groupid, u.name, u.phone
FROM   user_groups ug
JOIN   group_membership USING (groupid)
JOIN   users u          USING (userid)
WHERE  ug.activity = 'knitting';

Details in the manual here. 手册中的详细信息在这里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM