繁体   English   中英

将行嵌套到多个 json 对象中

[英]unnest row into multiple json objects

目前我有一个带有列 (id,product_id,text) 的表my_table并将数据转换为 json object ,如下所示:

SELECT
  json_agg(
    json_build_object(
      'id', t.id,
      'parent_id', t.product_id,
      'text', t.text
    )
  )
FROM my_table AS t

现在我要向my_table添加更多列,我需要从此表中选定的行列表中的每一行返回一个 JSON object 。 基本上,talbe 列将是 (id,product_id,text1,text2,text3)

我想返回 3 个具有 1 个不同文本值的相同对象(对于 text1、text2、text3)

我怎样才能做到这一点?

使用unnest()将单行生成为三行:

select id, product_id, unnest(array[text1, text2, text3]) as text
from my_table

从上述查询创建 json 数组:

select
    json_agg (
        json_build_object(
            'id', id,
            'product_id', product_id,
            'text', text
        )
    )
from (
    select id, product_id, unnest(array[text1, text2, text3]) as text
    from my_table
    ) t

或者

select
    json_agg (
        json_build_object(
            'id', id,
            'product_id', product_id,
            'text', text
        )
    )
from my_table
cross join unnest(array[text1, text2, text3]) as text

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM