【问题标题】:unnest row into multiple json objects将行嵌套到多个 json 对象中
【发布时间】:2019-11-13 18:44:08
【问题描述】:

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

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 对象。 基本上,talbe 列将是 (id,product_id,text1,text2,text3)

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

我怎样才能做到这一点?

【问题讨论】:

    标签: sql json database postgresql


    【解决方案1】:

    使用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
    

    【讨论】:

    • 非常感谢!我试图在我的FROM (...) 中使用unnest,但实际上我没有意识到它是如何工作的。
    • from 子句中的函数与横向连接一起使用可能更优雅,请参阅更新后的答案。
    • 对我来说,最初的答案更容易阅读。有什么理由应该选择后者吗?
    • 在这种情况下它们大致相同。无论如何,我建议使用第二种变体,因为它可能对更复杂的查询非常有帮助。
    • 我明白了。我会努力的!
    猜你喜欢
    • 2021-07-19
    • 2023-01-29
    • 1970-01-01
    • 2019-05-12
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 1970-01-01
    相关资源
    最近更新 更多