嵌套对象上的 Postgres jsonb 查询

Postgres jsonb query on nested object

我的 postgres 数据库版本:9.4.4。我有一个 table 这种结构;

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

我在 "data" 列中有这样的记录;

{"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 个 "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"

如果能指出正确的方向,我将不胜感激

使用json_agg() and 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