【问题标题】:how can I make result of ARRAY_AGG() function json parsable如何使 ARRAY_AGG() 函数的结果 json 可解析
【发布时间】:2023-02-09 14:43:12
【问题描述】:

我有一个查询,它使用 ARRAY_AGG() 函数从连接表中选择行作为数组。

select 
    entity_number, 
    ARRAY_AGG('{"property_id":"'||property_id||'","value":"'||value||'"}') entity_properties from entities
join entity_properties
on entities.id = entity_properties.entity_id
where entities.id in (
    select entity_id from entity_properties 
    where value = '6258006d824a25dabdb39a79.pdf'
)
group by entities.id;

我得到的是:

[
    {
        "entity_number":"P1718238009-1",
        "entity_properties":"[
            \"{\"property_id\":\"006109cd-a100-437c-a683-f13413b448e6\",\"value\":\"Rozilik berildi\"}\",
            \"{\"property_id\":\"010f5e23-d66f-4414-b54b-9647afc6762b\",\"value\":\"6258006d824a25dabdb39a79.pdf\"}\",
            \"{\"property_id\":\"0a01904e-1ca0-40ef-bbe1-c90eaddea3fc\",\"value\":\"6260c9e9b06e4c2cc492c470_2634467.pdf\"}\"
        ]"
    }
]

如您所见,它不是 json 可解析的

要将 entity_properties 解析为对象数组,我需要这种格式的数据

[
    {
        "entity_number":"P1718238009-1",
        "entity_properties":[
            {"property_id":"006109cd-a100-437c-a683-f13413b448e6","value":"Rozilik berildi"},
            {"property_id":"010f5e23-d66f-4414-b54b-9647afc6762b","value":"6258006d824a25dabdb39a79.pdf"},
            {"property_id":"0a01904e-1ca0-40ef-bbe1-c90eaddea3fc","value":"6260c9e9b06e4c2cc492c470_2634467.pdf"}
        ]
    }
]

我可以用ARRAY_AGG()实现我想要的吗?如何?

如果不是,我应该采取什么方法?

【问题讨论】:

    标签: sql postgresql aggregate-functions sql-function


    【解决方案1】:

    尝试使用json_aggjson_build_object 函数

    像这样:

    select 
        entity_number, 
        json_agg(json_build_object("property_id", property_id, "value", value)) entity_properties from entities
    join entity_properties
    on entities.id = entity_properties.entity_id
    where entities.id in (
        select entity_id from entity_properties 
        where value = '6258006d824a25dabdb39a79.pdf'
    )
    group by entities.id;
    

    【讨论】:

      猜你喜欢
      • 2012-05-02
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      相关资源
      最近更新 更多