Postgresql 查询 json 数组中的 json 元素
Postgresql query json element inside json array
我有一个 table 喜欢:
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"}]
我需要获取国家为 'CHINA' 且项目为“%test%”的不同 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"}]
我应该怎么做才能获得包含 'CHINA' 个国家/地区的对象数组?
使用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;
我有一个 table 喜欢:
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"}]
我需要获取国家为 'CHINA' 且项目为“%test%”的不同 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"}]
我应该怎么做才能获得包含 'CHINA' 个国家/地区的对象数组?
使用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;