jsonb-search仅显示规范值

时间:2017-08-28 14:52:09

标签: postgresql jsonb

我发现你们中的大多数人都在tread中寻找,但是我有问题从我的查询中找到正确的位,

jsonb-column看起来像这样:

[
{"price": 67587, "timestamp": "2016-02-11T06:51:30.696427Z"}, 
{"price": 33964, "timestamp": "2016-02-14T06:49:25.381834Z"}, 
{"price": 58385, "timestamp": "2016-02-19T06:57:05.819455Z"}, etc..
]

查询如下所示:

SELECT * FROM store_product_history 
WHERE EXISTS (SELECT 1 FROM jsonb_array_elements(store_prices) 
as j(data) WHERE (data#>> '{price}') LIKE '%236%');

当然这给了我结果的整行但是我想只得到行中的时间戳值,这可能吗?

1 个答案:

答案 0 :(得分:0)

如果在横向连接中使用jsonb_array_elements(),则可以选择单个json属性,例如

with store_product_history(store_prices) as (
values
('[
    {"price": 67587, "timestamp": "2016-02-11T06:51:30.696427Z"}, 
    {"price": 33964, "timestamp": "2016-02-14T06:49:25.381834Z"}, 
    {"price": 58385, "timestamp": "2016-02-19T06:57:05.819455Z"}
]'::jsonb)
)

select data
from store_product_history,
jsonb_array_elements(store_prices) as j(data) 
where (data#>> '{price}') like '%6%';

                             data                             
--------------------------------------------------------------
 {"price": 67587, "timestamp": "2016-02-11T06:51:30.696427Z"}
 {"price": 33964, "timestamp": "2016-02-14T06:49:25.381834Z"}
(2 rows)

或者:

select data->>'timestamp' as timestamp
from store_product_history,
jsonb_array_elements(store_prices) as j(data) 
where (data#>> '{price}') like '%6%';

          timestamp          
-----------------------------
 2016-02-11T06:51:30.696427Z
 2016-02-14T06:49:25.381834Z
(2 rows)