gpt4 book ai didi

postgresql - Postgres JSONB 数据类型 - 如何从 Postgres 数据库的 JSON(JsonB 类型)字段中提取数据?

转载 作者:行者123 更新时间:2023-11-29 14:30:48 36 4
gpt4 key购买 nike

friend 们好,我需要帮助来解决以下问题,

我在我的 postgres 数据库表中有一组记录,其中表有 JSONB 类型字段。

JSONB 类型列包含以下JSON,

记录#1 :-

{
"key1": "value1",
"key2": "value2",
"audience": [
{
"name": "Person1",
"email": "test1@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
},
{
"name": "Person2",
"email": "test2@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
}
]
}

记录#2:-

{
"key1": "value1",
"key2": "value2",
"audience": [
{
"name": "Person3",
"email": "test3@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
},
{
"name": "Person4",
"email": "test4@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
}
]
}

预期结果(获取所有受众):-

[
{
"name": "Person1",
"email": "test1@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
},
{
"name": "Person2",
"email": "test2@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
},
{
"name": "Person3",
"email": "test3@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
},
{
"name": "Person4",
"email": "test4@mail.com",
"country": "UK",
"primaryNumber": "+1234567890",
"secondaryNumber": "+1234567890"
}
]

任何人都可以帮助我设计native query 或通过spring-data-jpa 的查询吗?

如果有人能帮助我摆脱这种情况,我真的很感激!

最佳答案

您应该使用 jsonb_array_elements() 提取每一行的 'audience' 数组元素,并使用 jsonb_agg() 将它们聚合到单个 json 对象>:

select jsonb_agg(value)
from my_table
cross join jsonb_array_elements(json_data->'audience')

Working example in rextester.

关于postgresql - Postgres JSONB 数据类型 - 如何从 Postgres 数据库的 JSON(JsonB 类型)字段中提取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52182986/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com