我的 postgres(版本 10)表中有一个名为 json_col
的文本字段。我正在尝试使用 SQL 将两个数组 MyArray
和 impressions
扩展为多行
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
关于arrays - 使用 postgres 中的 json_array_elements 将 json 数组值转换为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63208560/