2017-08-16 31 views
1

我有2個表:PostgreSQL的json_array_elements

表組 - 編號(BIGSERIAL),名稱(VARCHAR),電子郵件(JSON)

表郵件 - 編號(BIGSERIAL),名稱(VARCHAR)

我在組

1, en-mails, [{"id" : 1}, {"id" : 2}] 
2, fr-mails, [{"id" : 3}, {"id" : 4}] 

我的數據的數據在郵件

1, [email protected] 
2, [email protected] 
3, [email protected] 
4, [email protected] 

我的查詢:

SELECT tg.name, tm.mail 
    FROM groups as tg 
    CROSS JOIN LATERAL json_array_elements (tg.mails :: json) group_mails 
    LEFT OUTER JOIN mails as tm ON (group_mails ->> 'id') :: BIGINT = tm.c_id 

我的結果

Array ([name] => en-mails [mail] => [email protected]) 
Array ([name] => en-mails [mail] => [email protected]) 
Array ([name] => fr-mails [mail] => [email protected]) 
Array ([name] => fr-mails [mail] => [email protected]) 

我的問題 - 如何查詢回報:

Array ([name] => en-mails [mail] => [[email protected], [email protected]]) 
Array ([name] => fr-mails [mail] => [[email protected], [email protected]]) 

在此先感謝

回答

0

使用聚合函數array_agg()

SELECT tg.name, array_agg(tm.mail) as mail 
FROM groups as tg 
CROSS JOIN LATERAL json_array_elements (tg.mails :: json) group_mails 
LEFT OUTER JOIN mails as tm ON (group_mails ->> 'id') :: BIGINT = tm.id 
GROUP BY 1 

    name |    mail     
----------+----------------------------------- 
en-mails | {[email protected],[email protected]} 
fr-mails | {[email protected],[email protected]} 
(2 rows)  
+0

完美的作品!非常感謝! – lveselinov

+0

我還有一個問題 - 是否有辦法分頁json(group_mails - >>'id') - offcet 0 limit count(group_mails)? – lveselinov

+0

我不確定我是否理解這個問題。也許問一個更詳細的問題描述一個新的問題。 – klin