在JSON值中找不到整个数组中的值

问题描述

PostgreSQL 9.6

json:

 "availability": [
      {
        "qty": 25,"price": 3599,"is_available": true
      },{
        "qty": 72,},"is_available": true
   ]

假设我要搜索第一个数组的项目。我使用以下查询:

SELECT product.data #>'{availability,price}' from product

好。 但是我需要找到整个数组(所有数组项)。

我需要这样的smt(伪代码

SELECT product.data #>'{availability,*,price}' from product

有可能吗?

解决方法

如果找不到价格,

输出必须为空数组;如果以任何价格找到

,则输出必须为原始json。

听起来像一个奇怪的要求,但是下面的方法可以做到。

select case 
           when (select jsonb_agg(e.item -> 'price') 
                 from jsonb_array_elements(data -> 'availability')  as e(item)
                 where e.item ? 'price') <> '[]' then data
           else '[]'::jsonb
       end
from product

在我看来,简单的价格数组更有意义:

select (select jsonb_agg(e.item -> 'price') 
        from jsonb_array_elements(data -> 'availability')  as e(item)
        where e.item ? 'price') as prices
from product

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...