2015-02-10 30 views
1

我有3個表,看起來依稀像這樣:寫作加入PostgreSQL的查詢多個表

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

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

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

我試圖與會員承擔一定的打印用戶姓名和電話號碼的所有組活動。例如,第1組活動=編織,第2組活動=縫紉和第3組活動=編織。我想選擇所有正在編織的成員,但我不確定如何在一個查詢中連接三個表。這是我試過到目前爲止:

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

這最終引發了以下錯誤:

ERROR: missing FROM-clause entry for table "groups"

爲了解決這個問題我嘗試添加teamsFROM條款,像這樣:

FROM users,groups 

但是,這反過來給我這個錯誤:

ERROR: invalid reference to FROM-clause entry for table "members"

任何幫助在這裏將不勝感激。

回答

0

嘗試這個

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'; 
0

你可以有更短的用表的別名和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.