You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL:将string_agg生成的文本列转为jsonb的查询改写求助

PostgreSQL TEXT转JSONB类型的records列查询改写

原场景与问题

原本通过字符串拼接生成JSON格式数据,插入到TEXT类型的records列中。现在该列改为JSONB类型,需要用jsonb_build_object和jsonb_object_agg改写原查询,避免手动拼接的语法风险。

原查询代码

select 'my_table' as name,
    '{"my_table":{' ||
    string_agg('"' || nr || code || '":{"code":"' || nr || code || '","name_eng":"' || eng || '","name_de":"' || de || '","name_se":"' || se || '","nr_cd":"' || nr || '","code":"' || code || '"}', ',') || '}}' as records,
    '[{"attribut":"nr_cd","codetable_type":"String"},{"attribut":"cus_immopaccode","codetable_type":"String"}]' as custom_attributes
from (select '01' as code, 'Rat' as eng, 'Ratte' as de, 'Ratta' se 
        union all select  '02', 'Cow','Kuh','Ko'
        union all select  '03', 'Dog','Hund','Hund'
        union all select  '04', 'Cat','Katze','Katt'
    )d
        cross join (select '1' as nr 
                union all select '2'
                union all select '3'
                )m  

改写后的JSONB版本查询

select 
    'my_table' as name,
    jsonb_build_object(
        'my_table',
        jsonb_object_agg(
            nr || code,
            jsonb_build_object(
                'code', nr || code,
                'name_eng', eng,
                'name_de', de,
                'name_se', se,
                'nr_cd', nr,
                'code', code
            )
        )
    ) as records,
    '[{"attribut":"nr_cd","codetable_type":"String"},{"attribut":"cus_immopaccode","codetable_type":"String"}]'::jsonb as custom_attributes
from (select '01' as code, 'Rat' as eng, 'Ratte' as de, 'Ratta' se 
        union all select  '02', 'Cow','Kuh','Ko'
        union all select  '03', 'Dog','Hund','Hund'
        union all select  '04', 'Cat','Katze','Katt'
    )d
cross join (select '1' as nr 
            union all select '2'
            union all select '3'
           )m  

关键改写说明

  • jsonb_build_object:替代字符串拼接,直接构建键值对形式的JSONB对象,自动处理转义逻辑,避免语法错误。
  • jsonb_object_agg:将多行数据聚合为单个JSONB对象,第一个参数是对象的唯一键(此处用nr || code拼接生成),第二个参数是对应的值(由内层jsonb_build_object生成的子对象)。
  • 外层用jsonb_build_object包裹my_table键,对应聚合后的JSONB对象,完全匹配原查询的结构。
  • custom_attributes列也转为JSONB类型(通过::jsonb强制转换),更贴合JSONB列的存储特性。

内容的提问来源于stack exchange,提问作者user2210516

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 15:50:15