2017-08-28 28 views
1

我发现大多数的你追问这个tread,但我有问题可以得到正确的位出我的查询,jsonb搜索,只显示规格值

的jsonb列如下:

[ 
{"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%'); 

这当然给了我完整行的结果,但我想只得到像从行唯一的时间戳值,我这可能吗?

回答

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)