arrays - 使用 postgres 中的 json_array_elements 将 json 数组值转换为多行

标签 arrays json postgresql

我的 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

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

最佳答案

你可以这样尝试:

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

关于arrays - 使用 postgres 中的 json_array_elements 将 json 数组值转换为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63208560/

相关文章:

javascript - 如何将数组粘贴到另一个数组中?

c++ - 显示二维动态数组

sql - postgresql,奇怪的 OFFSET/LIMIT 行为(记录顺序)

java - 需要仅更新java中mongo数组中的特定元素

javascript - 在数组js中根据条件进行归约

regex - Nodejs : JSONStream parse method regex

javascript - 使用 JSON 在 HTML 数据属性中传递数据

json - 当键是非字符串对象时,是否可以将 .NET 字典 JSON 化?

将新目录添加到 PostgreSQL 表中的 Bash 脚本

sql - Postgres - 将列移动到另一个表或更新另一列