查询嵌套结构中的 JSONB 列
Querying JSONB column in nested structure
我以前从未使用过 JSONB 列,所以我正在努力处理一个简单的查询。
我需要 select 下面这个 json 中的所有 value 字段。输出应为:value1, value2, value3, value4, value5, value6, value7, value8
就我所知,但我找不到更深入 json 的方法。
SELECT 结果 -> 'report' ->> 'products' AS 值来自 example_table
感谢您的帮助。
CREATE TABLE example_table(
id SERIAL PRIMARY KEY,
result JSONB NOT NULL);
INSERT INTO example_table(result)
VALUES('{
"report": {
"products": [
{
"productName": "Product One",
"types": [
{
"type": "Type One",
"metadata": {
"prices": [
{
"price": {
"value": "value1"
}
},
{
"price": {
"value": "value2"
}
}
]
}
},
{
"type": "Type Two",
"metadata": {
"prices": [
{
"price": {
"value": "value3"
}
},
{
"price": {
"value": "value4"
}
}
]
}
}
]
},
{
"productName": "Product Two",
"types": [
{
"type": "Type One",
"metadata": {
"prices": [
{
"price": {
"value": "value5"
}
},
{
"price": {
"value": "value6"
}
}
]
}
},
{
"type": "Type Two",
"metadata": {
"prices": [
{
"price": {
"value": "value7"
}
},
{
"price": {
"value": "value8"
}
}
]
}
}
]
}
]
}
}');
您应该使用 CROSS JOIN
和 jsonb_array_elements
函数为记录的每个元素提取数组
select
et.id,
string_agg(ptmp.value -> 'price' ->> 'value', ',')
from
example_table et
cross join jsonb_array_elements(et.result -> 'report' -> 'products') p
cross join jsonb_array_elements (p.value -> 'types') pt
cross join jsonb_array_elements (pt.value -> 'metadata' -> 'prices') ptmp
group by et.id
我以前从未使用过 JSONB 列,所以我正在努力处理一个简单的查询。
我需要 select 下面这个 json 中的所有 value 字段。输出应为:value1, value2, value3, value4, value5, value6, value7, value8
就我所知,但我找不到更深入 json 的方法。
SELECT 结果 -> 'report' ->> 'products' AS 值来自 example_table
感谢您的帮助。
CREATE TABLE example_table(
id SERIAL PRIMARY KEY,
result JSONB NOT NULL);
INSERT INTO example_table(result)
VALUES('{
"report": {
"products": [
{
"productName": "Product One",
"types": [
{
"type": "Type One",
"metadata": {
"prices": [
{
"price": {
"value": "value1"
}
},
{
"price": {
"value": "value2"
}
}
]
}
},
{
"type": "Type Two",
"metadata": {
"prices": [
{
"price": {
"value": "value3"
}
},
{
"price": {
"value": "value4"
}
}
]
}
}
]
},
{
"productName": "Product Two",
"types": [
{
"type": "Type One",
"metadata": {
"prices": [
{
"price": {
"value": "value5"
}
},
{
"price": {
"value": "value6"
}
}
]
}
},
{
"type": "Type Two",
"metadata": {
"prices": [
{
"price": {
"value": "value7"
}
},
{
"price": {
"value": "value8"
}
}
]
}
}
]
}
]
}
}');
您应该使用 CROSS JOIN
和 jsonb_array_elements
函数为记录的每个元素提取数组
select
et.id,
string_agg(ptmp.value -> 'price' ->> 'value', ',')
from
example_table et
cross join jsonb_array_elements(et.result -> 'report' -> 'products') p
cross join jsonb_array_elements (p.value -> 'types') pt
cross join jsonb_array_elements (pt.value -> 'metadata' -> 'prices') ptmp
group by et.id