2016-05-28 53 views
0

我有一個表,如:PostgreSQL的查詢JSON元素

CREATE TABLE stats 
(
    item character varying, 
    data jsonb 
); 

it contains values like 
ITEM  DATA 
test1  [{"id":"1", "country":"UK"},{"id":"2", "country":"INDIA"}] 
test2  [{"id":"1", "country":"US"},{"id":"4", "country":"CHINA"},{"id":"5", "country":"CHINA"}] 

我需要不同的JSON對象的數量,其中國家是「中國」和產品「%測試%」; 在這種情況下,輸出應該是2,即[{「id」:「4」,「country」:「CHINA」},{「id」:「5」,「country」:「CHINA」}]

我使用下面的查詢

SELECT * FROM stats t 
WHERE (data @> '[{"country":"CHINA"}]') 
and t.item ilike '%test%'; 

output : [{"id":"1", "country":"US"},{"id":"4", "country":"CHINA"},{"id":"5", "country":"CHINA"}] 

我應該做的,這樣我得到的對象數組其中有「中國」作爲國家?

回答

0

使用jsonb_array_elements()來獲取單個json對象,過濾它們並使用jsonb_agg()聚合成一個json數組。

select item, jsonb_agg(obj) 
from stats, jsonb_array_elements(data) obj 
where obj->>'country' = 'CHINA' 
group by 1; 
+0

ERROR:功能jsonb_agg(jsonb)不存在 SQL狀態:42883 – ranjan

+0

['jsonb_agg()'](https://www.postgresql.org/docs/9.5/static/functions-aggregate。 html)在當前的(9.5)Postgres版本中可用。在Postgres 9.4中,你可以試試['json_agg()'](https://www.postgresql.org/docs/9.4/static/functions-aggregate.html)。 – klin