【问题标题】:Converting json array value to multiple rows using json_array_elements in postgres使用 postgres 中的 json_array_elements 将 json 数组值转换为多行
【发布时间】:2020-08-01 18:13:46
【问题描述】:

我的 postgres(版本 10)表中有一个名为 json_col 的文本字段。我正在尝试使用 SQL 将两个数组 MyArrayimpressions 扩展为多行

select 
json_col::json -> 'content'->>'objectID' as objectID
,json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue
,json_array_elements(json_col::json -> 'content'->'impressions')->>'intent' as intent
from my_pg_table 

样本数据

{   "content": {
    "objectID": "ABC",
    "ObjectType": "MyType",
    "MyArray": [
      "Blue",
      "Black"
    ],
    "impressions": [
      {
        "intent": "Large"
      },
      {
        "intent": "Small"
      },
      {
        "intent": "Regular"
      },
      {
        "intent": "Medium"
      }
    ]   } }

在输出中,我得到了预期的外部数组(印象数)。第一个数组(MyArray)也扩展到多行,但它不会为第一个数组扩展创建的每条记录创建行。

我得到这样的输出。

  objectID  intent  MyArrayValue
   
   ABC  Large   Blue
   
   ABC  Small   Black
   
   ABC  Regular [NULL]
   
   ABC  Medium  [NULL]

但我正在寻找如下输出。

objectID    intent  MyArrayValue

ABC Large   Blue

ABC Large   Black

ABC Small   Blue

ABC Small   Black

ABC Regular Blue

ABC Regular Black

ABC Medium  Blue

ABC Medium  Black

如果您有任何意见,请告诉我。

【问题讨论】:

    标签: arrays json postgresql


    【解决方案1】:

    你可以这样试试:

    with cte as (
    select 
    json_col::json -> 'content'->>'objectID' as objectID
    ,json_array_elements(json_col::json -> 'content'->'impressions')->>'intent' as intent
    from my_pg_table 
    ),
    cte1 as 
    (
    select 
    json_col::json -> 'content'->>'objectID' as objectID
    ,json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue
    from my_pg_table
    )
    
    select 
    t1.objectID,t1.intent,t2.myarrayvalue
    from cte t1 inner join cte1 t2 on t1.objectID=t2.objectID
    

    DEMO

    【讨论】:

    • 谢谢@Akhilesh。我也有如下方法,不知何故我无法将它应用到 select 语句的顶部。我将继续使用加入方法。 select a,b from unnest(array[1,2]) a,lateral unnest(array[1,2,3]) b;
    【解决方案2】:

    在横向连接中使用该函数:

    select 
        json_col::json -> 'content'->>'objectID' as objectID,
        impressions->>'intent' as intent,
        MyArrayValue
    from my_pg_table
    cross join json_array_elements(json_col::json -> 'content'->'impressions') as impressions
    cross join json_array_elements_text(json_col::json -> 'content'->'MyArray') as MyArrayValue
    

    Db<>fiddle.

    【讨论】:

    • 谢谢@klin,我也有如下方法,不知何故我无法将它应用到 select 语句之上。我将继续使用加入方法。 select a,b from unnest(array[1,2]) a,lateral unnest(array[1,2,3]) b;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2015-10-24
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多