从json数组对象postgres获取价值

时间:2020-06-08 23:46:48

标签: sql arrays json postgresql select

我有这样的查询:

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"}]

...

好吧,我想查询SERIE NUMBER等于00.000.000-11的行。 有过滤的方法吗?

1 个答案:

答案 0 :(得分:0)

您可以使用HAVING子句过滤聚合查询。还要注意,这里不需要子查询,并且WHERE子句与ON的{​​{1}}子句一起被替换。

所以:

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有什么理由吗?后者提供了更多的功能,通常应优先选择。您可以使用jsonbjsonb_build_objet()代替相应的jsonb_agg()函数。