鉴于下表:
# create table thing (id serial, tags jsonb);
# \d thing
Table "public.thing"
Column | Type | Modifiers
--------+---------+----------------------------------------------------
id | integer | not null default nextval('thing_id_seq'::regclass)
tags | jsonb |
......以及以下数据:
insert into thing (tags) values ('{"tag1": ["val1", "val2"], "tag2": ["t2val1"]}');
insert into thing (tags) values ('{"tag1": ["val3", "val1"], "tag2": ["t2val1"]}');
insert into thing (tags) values ('{"tag1": ["val2", "val1"], "tag2": ["t2val2"]}');
如何聚合等同于“向我显示匹配行数和tag1
值tag2
值t2val1
的查询结果?< / p>
我能得到的结果是:
# select count(*), json_agg(tags) from thing where tags->'tag2'?'t2val1';
count | json_agg
-------+--------------------------------------------------------------------------------------------------
2 | [{"tag1": ["val1", "val2"], "tag2": ["t2val1"]}, {"tag1": ["val3", "val1"], "tag2": ["t2val1"]}]
(1 row)
......但我真的想要:
count | tag1
-------+-------------------------
2 | ["val1", "val2", "val3"]
(1 row)