为什么 PostgreSQL json_agg() 函数不返回空数组? [英] Why PostgreSQL json_agg() function does not return an empty array?
本文介绍了为什么 PostgreSQL json_agg() 函数不返回空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 json_agg
函数从 PostgreSQL 请求返回一个 JSON 数组.但是,当没有找到行时,json_agg
返回一个空字符串而不是一个空的 JSON 数组 []
(如果我理解 json.org).
I'm returning a JSON array from a PostgreSQL request with the json_agg
function. However, when no row is found, json_agg
returns an empty string instead of an empty JSON array []
(square brackets are mandatory if I understand json.org).
例如:
SELECT json_agg(t.*) FROM (SELECT 'test' AS mycol WHERE 1 = 2) AS t ;
返回一个空字符串,而带有 '1 = 1' 的相同命令返回一个有效的 JSON 数组(使用 PostgreSQL 9.5 测试).
returns an empty string, whereas the same command with '1 = 1' returns a valid JSON array (tested with PostgreSQL 9.5).
有什么想法吗?
推荐答案
json_agg
从空集返回 null:
json_agg
returns null from an empty set:
select json_agg(t.*) is null
from (select 'test' as mycol where 1 = 2) t ;
?column?
----------
t
如果你想要一个空的 json 数组 coalesce
它:
If you want an empty json array coalesce
it:
select coalesce(json_agg(t.*), '[]'::json)
from (select 'test' as mycol where 1 = 2) t ;
coalesce
----------
[]
这篇关于为什么 PostgreSQL json_agg() 函数不返回空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文