簡體   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