简体   繁体   English

按键/值过滤 JSON 数组元素的 PostgreSQL (v9.6) 查询

[英]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 .我们需要构造几个查询来过滤SELECTSUMitems[]数组的特定元素。

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但是我们如何获得子查询

  • select only basket items of type-A仅选择类型 A 的篮子项目
  • sum of prices of items of type-A A类商品的总价

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM