PostgreSQL-JSONB ARRAY-作为单个JSON ARRAY处理后获得结果

时间:2019-02-05 07:04:43

标签: sql postgresql

我们正在使用postgresql 10.5。我有以下架构和数据。

 create table contacts (
    contact_seq text,
    address jsonb
);

insert into contacts values ('1', '[
{ "name": "Jagan",  "email_address": "jagan@xxx.com"} , 
 { "name": "raja",  "email_address": "raja@xxx.com"}  ]')

 select contact_seq, address.email_address from contacts contacts, 
 jsonb_to_recordset(contacts.address) as address(email_address text) where contact_seq = '1'

上面的选择查询正确返回了电子邮件地址。但是,它将结果返回为2个不同的行。有可能将结果作为json数组放在一行中吗?还是应该仅使用子查询来实现这一目标?

2 个答案:

答案 0 :(得分:0)

如果您知道只有两个地址,则可以直接访问数组元素:

select contact_seq, 
       (address -> 0) ->> 'email_address' as email_one,
       (address -> 1) ->> 'email_address' as email_two
from contacts
where contact_seq = '1';

要将它们作为JSON数组获取,可以使用子选择:

select contact_seq, 
       (select jsonb_agg(t -> 'email_address') 
        from jsonb_array_elements(address) as x(t)) as emails
from contacts
where contact_seq = '1';

答案 1 :(得分:0)

字符串AGG可以帮助您

select contact_seq,
string_agg(address.email_address,',') 
from contacts contacts, 
jsonb_to_recordset(contacts.address) as address(email_address text)
where contact_seq = '1'
group by contact_seq

输出-

+-------------+----------------------------+
| contact_seq |         string_agg         |
+-------------+----------------------------+
|           1 | jagan@xxx.com,raja@xxx.com |
+-------------+----------------------------+

如果需要,可以通过串联操作以获取JSON字符串