[英]PostgreSQL (v9.6) query that filters JSON array elements by key/value
We have a jsonb
column with data of the type:我们有一个
jsonb
以下类型数据的jsonb
列:
"basket": {
"total": 6,
"items": [
{ "type": "A", "name": "A", "price": 1 },
{ "type": "A", "name": "B", "price": 2 },
{ "type": "C", "name": "C", "price": 3 },
]
}
We need to construct few queries that will filter specific elements of the items[]
array for SELECT
and SUM
.我们需要构造几个查询来过滤
SELECT
和SUM
的items[]
数组的特定元素。
We have PG v9.6 so using jsonb_path_query_array
didn't work.我们有 PG v9.6,所以使用
jsonb_path_query_array
不起作用。
Using basket->'items' @> '{"type":"A"}'
works to find all entries that has type-A.使用
basket->'items' @> '{"type":"A"}'
可以找到所有类型为 A 的条目。
But how do we get subquery to但是我们如何获得子查询
Thank you!谢谢!
This will select the required items:这将选择所需的项目:
select * from jsonb_array_elements('{"basket":
{
"total": 6,
"items": [
{ "type": "A", "name": "A", "price": 1 },
{ "type": "A", "name": "B", "price": 2 },
{ "type": "C", "name": "C", "price": 3 }
]
}}'::jsonb#>'{basket,items}') e(it)
where it->>'type' = 'A';
and this the sum of prices:这是价格的总和:
select sum(cast(it->>'price' as numeric)) from jsonb_array_elements('{"basket":
{
"total": 6,
"items": [
{ "type": "A", "name": "A", "price": 1 },
{ "type": "A", "name": "B", "price": 2 },
{ "type": "C", "name": "C", "price": 3 }
]
}}'::jsonb#>'{basket,items}') e(it)
where it->>'type' = 'A';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.