2016-05-24 52 views
0

我運行下面的查詢每次用戶登錄時獲得的相關數據Postgres的回報,如果橫向加入犯規取

SELECT ac.username,ac.password, 
(array_agg(json_build_object('message',pm.message,'username',pm.username,'message_id',pm.message_id)))[0:10] AS messages, 
p.project_name,p.project_id 
FROM account ac, 
LATERAL(SELECT * FROM accounts_projects WHERE ac.user_id = accounts_projects.account_id) ap, 
LATERAL(SELECT * FROM project_messages WHERE ap.project_id = project_messages.project_id ORDER BY project_messages.message_id) pm, 
LATERAL(SELECT * FROM project WHERE project.project_id = ap.project_id) p 
WHERE ac.username=$1 
GROUP BY p.project_name,p.project_id,ac.user_id; 

可以說,任何行空表我有2個用戶 -

用戶1加盟項目(accounts_projects表) - >他得到下面的輸出

username: 'kannaj', 
    projects: 
    [ { project_name: 'Machine Learning with Python', 
     messages: [Object], 
     project_id: 1 }, 
    { project_name: 'Beethoven with react', 
     messages: [Object], 
     project_id: 3 }, 
    { project_name: 'Football with Javascript', 
     messages: [Object], 
     project_id: 2 } ] } 

但是,如果那裏有誰不屬於accounts_projects一個新的用戶。 postgres返回一個空行。即只是根據用戶名和其他列的空值獲取ac.user_id &密碼?

是否有無論如何我可以得到postgres 忽略或者如果沒有找到數據發現橫向連接返回null?理想情況下,只能獲取ac.username和ac.password。

它看起來像一個簡單的左連接應該做的伎倆。我試圖更新這樣

LEFT JOIN LATERAL(SELECT * FROM accounts_projects WHERE ac.user_id = accounts_projects.account_id) ap, 
LEFT JOIN LATERAL(SELECT * FROM project_messages WHERE ap.project_id = project_messages.project_id ORDER BY project_messages.message_id) pm, 
LEFT JOIN LATERAL(SELECT * FROM project WHERE project.project_id = ap.project_id) p 

查詢,但我得到了下面的錯誤

ERROR: syntax error at or near "JOIN" 
LINE 6: LEFT JOIN LATERAL(SELECT * FROM accounts_projects WHERE ac.u... 
      ^
********** Error ********** 

ERROR: syntax error at or near "JOIN" 
SQL state: 42601 
Character: 206 
+0

使用'左加入橫向(...)上TRUE'代替。 – Abelisto

+0

@Abelisto - 我剛剛更新了問題..我沒有使用左連接..但我得到一個語法錯誤:(..我還沒有嘗試'在真正的'雖然 – Kannaj

+0

是啊..事實上我不需要請使用逗號:/ – Kannaj

回答

1

嘗試:

SELECT ac.username,ac.password, 
(array_agg(json_build_object('message',pm.message,'username',pm.username,'message_id',pm.message_id)))[0:10] AS messages, 
p.project_name,p.project_id 
FROM account ac 
LEFT JOIN LATERAL(SELECT * FROM accounts_projects WHERE ac.user_id = accounts_projects.account_id) ap ON TRUE 
LEFT JOIN LATERAL(SELECT * FROM project_messages WHERE ap.project_id = project_messages.project_id ORDER BY project_messages.message_id) pm ON TRUE 
LEFT JOIN LATERAL(SELECT * FROM project WHERE project.project_id = ap.project_id) p ON TRUE 
WHERE ac.username=$1 
GROUP BY p.project_name,p.project_id,ac.user_id;