从json数组对象postgres获取值

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

我有这样一个问题:

SELECT tags
FROM (
    SELECT trm.dado_id
        , json_agg(json_build_object('field',trm.nome, 'value',trm.valor)) AS tags
    FROM tb_dados trm
    JOIN tb_table1 t on trm.dado_id = t.id
    WHERE t.id = trm.dado_id
    GROUP BY trm.dado_id
    ) tabletags;

它返回了很多带有json数组字段的行,如下所示:

1  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-11"}]
2  |   [{"field" : "DATA CREATION", "value" : "21/09/1998"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-7"}]
3  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-7"}]
4  |   [{"field" : "EMISSION", "value" : "21/04/2020 00:38:00"}, {"field" : "DATA CREATION", "value" : "21/09/1989"}, {"field" : "SERIE NUMBER", "value" : "00.000.000-11"}]

...
我想查询序列号为00.000.000-11的行。有办法过滤吗?

mklgxw1f

mklgxw1f1#

可以使用 HAVING 条款。还要注意,子查询在这里不是必需的,并且 WHERE 子句与 ON 合同条款 JOIN .
所以:

SELECT json_agg(json_build_object('field', trm.nome, 'value', trm.valor)) AS tags
FROM tb_dados trm
JOIN tb_table1 t on trm.dado_id = t.id
GROUP BY trm.dado_id
HAVING bool_or(trm.nome = 'SERIE NUMBER' AND trm.valor = '00.000.000-11')

旁注:你为什么要使用 json 而不是 jsonb ? 后者提供了更多的功能,应该是普遍的首选。你可以用 jsonb_build_objet() 以及 jsonb_agg() 而不是相应的 json_* 功能。

相关问题