按键和值查询where子句中的json\u数组

3pvhb19x  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(379)

我有一个select查询,它返回一个数组到json对象。我想根据特定的键和值过滤select的结果。
我的实际问题是:

select jsonarray
from (
         SELECT body.id_user,
                array_to_json(array_agg(row_to_json(body))) as jsonarray
         FROM (
                  SELECT  id_user, name, value
                  FROM table_1
                  group by id_user, name, value
              ) body
         group by body.id_user
     ) as test;

它返回很多这样的行:

[{"id_user": 1489, "name": "name 1", "value": "value aaaaaa"},  {"id_user": 1489, "name": "name 2", "value": "value babababab"}]

[{ "id_user": 1490, "name": "name 12", "value": "value aaaaaa"  }, { "id_user": 1490, "name": "name 2",  "value": "value babababab" }]

[ { "id_user": 1491, "name": "name 13", "value": "value aaaaaa"  }, { "id_user": 1491,  "name": "name 23",  "value": "value uouououo" }]

好吧,我只希望json中包含字段“name”:“name 2”,“value”:“value babbab”的行。。。我试过了

select jsonarray->'name'
from (
....
     ) as test
where jsonarray->>'name'::text = 'name 2';

但它什么也不回。还有别的方法可以查询吗?

igetnqfo

igetnqfo1#

你可以检查一下 name 2 聚合期间存在:

SELECT jsonb_agg(to_jsonb(body)) as jsonarray
FROM (
  SELECT DISTINCT id_user, name, value
  FROM table_1
) body
group by body.id_user
having bool_or(name = 'name 2') -- those with at least one `name = 'name 2'`

在线示例

相关问题