Postgres jsonb查询嵌套对象

时间:2015-09-14 18:17:30

标签: postgresql jsonb

我的postgres db版本:9.4.4。我有一个这种结构的表格;

CREATE TABLE product_cust
(
 productid character(2),
  data jsonb,
)

我在“数据”栏中有这样的记录;

{"productid":"01","cust": [
        {"cell": ["0000xxx0", "0000xxx1"], "name": "John", "email": ["john@email.net"], "custtype": "c"}, 
        {"cell": ["0000xxx2", "0000xxx3"], "name": "Smith", "email": ["smith@email.net"], "custtype": "c"}  
]}

我需要提取“cell”的所有记录。预计记录将是

["0000xxx0", "0000xxx1","0000xxx2", "0000xxx3"] 

或“email”["john@email.net","smith@email.net"]

我下面的最好的努力是两步(2)步骤,并且不会缩放x“no”“cust”对象;

select (data::json#>'{cust,0}')::json#>'{cell}' from product_cust; //return "0000xxx0", "0000xxx1"
select (data::json#>'{cust,1}')::json#>'{cell}' from product_cust; //return "0000xxx2", "0000xxx3"

如果我能指出正确的方向,我将非常感激

1 个答案:

答案 0 :(得分:4)

使用json_agg()jsonb_array_elements()函数:

select json_agg(cell)
from (
    select jsonb_array_elements(elem->'cell') cell
    from (
        select jsonb_array_elements(data->'cust') elem
        from product_cust
        ) subsub
    ) sub

您可以合并两个内部子查询:

select json_agg(cell)
from (
    select jsonb_array_elements(jsonb_array_elements(data->'cust')->'cell') cell
    from product_cust
    ) sub

按productid分组结果:

select productid, json_agg(cell)
from (
    select productid, jsonb_array_elements(jsonb_array_elements(data->'cust')->'cell') cell
    from product_cust
    ) sub
group by 1
order by 1