我有这样的查询:
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的行。 有过滤的方法吗?
答案 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
有什么理由吗?后者提供了更多的功能,通常应优先选择。您可以使用jsonb
和jsonb_build_objet()
代替相应的jsonb_agg()
函数。