如何从 postgres jsonb 嵌套数组中获取字段
How to get field from postgres jsonb nested array
我的 table 中有一个 jsonb 列。
有一个数据
[
{
"name":"Гарнир",
"num_max":1,
"num_min":1,
"modifications":[
{
"name":"Салат Вінегрет",
"price":48,
"brutto":1,
"ingredient_id":33,
"dish_modification_id":1
},
{
"name":"Картошка фри",
"price":24,
"brutto":150,
"ingredient_id":28,
"dish_modification_id":2
},
{
"name":"Говядина",
"price":54,
"brutto":150,
"ingredient_id":19,
"dish_modification_id":22
},
{
"name":"Соус «Цезарь»",
"price":27.6,
"brutto":50,
"ingredient_id":6,
"dish_modification_id":23
}
],
"dish_modification_group_id":1
},
{
"name":"Напитки",
"num_max":1,
"num_min":1,
"modifications":[
{
"name":"Десерт Alphonso",
"price":66,
"brutto":1,
"ingredient_id":11,
"dish_modification_id":9
}
],
"dish_modification_group_id":4
}
]
我需要通过 product_id(整数 table 字段)和“dish_modification_id”获取“价格”字段。
怎么做?
这是我的建议。您当然可以添加 where
和其他子句。
with t(x) as
(
select j from jsonb_array_elements('... put your JSON data here ...'::jsonb) j
)
select (e ->> 'price')::numeric, (e ->> 'dish_modification_id')::numeric
from t
cross join lateral jsonb_array_elements(t.x -> 'modifications') e;
另一个(可能更干净)版本。先压扁再select.
with t(jsondata) as
(
select '... put your JSON data here ...'::jsonb
)
select (e ->> 'price')::numeric, (e ->> 'dish_modification_id')::numeric
from t
cross join lateral jsonb_array_elements(jsondata) ext_array
cross join lateral jsonb_array_elements(ext_array -> 'modifications') e;
运行 示例 here.
我的 table 中有一个 jsonb 列。 有一个数据
[
{
"name":"Гарнир",
"num_max":1,
"num_min":1,
"modifications":[
{
"name":"Салат Вінегрет",
"price":48,
"brutto":1,
"ingredient_id":33,
"dish_modification_id":1
},
{
"name":"Картошка фри",
"price":24,
"brutto":150,
"ingredient_id":28,
"dish_modification_id":2
},
{
"name":"Говядина",
"price":54,
"brutto":150,
"ingredient_id":19,
"dish_modification_id":22
},
{
"name":"Соус «Цезарь»",
"price":27.6,
"brutto":50,
"ingredient_id":6,
"dish_modification_id":23
}
],
"dish_modification_group_id":1
},
{
"name":"Напитки",
"num_max":1,
"num_min":1,
"modifications":[
{
"name":"Десерт Alphonso",
"price":66,
"brutto":1,
"ingredient_id":11,
"dish_modification_id":9
}
],
"dish_modification_group_id":4
}
]
我需要通过 product_id(整数 table 字段)和“dish_modification_id”获取“价格”字段。 怎么做?
这是我的建议。您当然可以添加 where
和其他子句。
with t(x) as
(
select j from jsonb_array_elements('... put your JSON data here ...'::jsonb) j
)
select (e ->> 'price')::numeric, (e ->> 'dish_modification_id')::numeric
from t
cross join lateral jsonb_array_elements(t.x -> 'modifications') e;
另一个(可能更干净)版本。先压扁再select.
with t(jsondata) as
(
select '... put your JSON data here ...'::jsonb
)
select (e ->> 'price')::numeric, (e ->> 'dish_modification_id')::numeric
from t
cross join lateral jsonb_array_elements(jsondata) ext_array
cross join lateral jsonb_array_elements(ext_array -> 'modifications') e;
运行 示例 here.