我有一个观点:
CREATE OR REPLACE VIEW microservice_view AS
SELECT
m.id :: BIGINT,
m.name,
m.sending_message_rate :: BIGINT,
m.max_message_size :: BIGINT,
m.prefetch_count :: BIGINT,
(SELECT COALESCE(json_agg(DISTINCT node_id), '[]')
FROM public.microservice_node
WHERE microservice_id = m.id) AS nodes,
(SELECT array_agg(DISTINCT json_build_object('id', transport_id :: INT,
'is_available', (credentials ->> 'is_available') :: BOOLEAN,
'username', credentials ->> 'username',
'password', credentials ->> 'password',
'default', (default_transport) :: BOOLEAN) :: JSONB
)
FROM transport_microservice
WHERE microservice_id = m.id) AS transports
FROM public.microservice m
GROUP BY m.id
ORDER BY m.id ASC;
有时传输为空。如何将空数组设置为 array_agg 的默认值?该字段应该是空数组或包含数据的数组。在某些情况下,我使用 array_length 函数来过滤数据。
最佳答案
首先,我不会将 array_agg
与 JSON 混合使用(注意双引号转义;我还使用 select array( .. subquery ..)
技巧来得到一个数组,它在某种程度上等同于你的 array_agg(..)
:
test=# select array(select '{"zz": 1}'::jsonb);
array
-----------------
{"{\"zz\": 1}"}
-- 在这里您将获得 JSONB 的数组,而您真正需要的是带有嵌入式数组的单个 JSONB 值:
test=# select pg_typeof(array(select '{"zz": 1}'::jsonb));
pg_typeof
-----------
jsonb[]
(1 row)
test=# select pg_typeof('[{"zz": 1}]'::jsonb);
pg_typeof
-----------
jsonb
(1 row)
要获取单个 jsonb
值(内部包含 JSON 数组),请使用 jsonb_agg(..)
函数。
如往常一样,要用一些默认值替换 NULL
值,您可以使用标准函数 coalesce(..)
:
test=# select coalesce(null::jsonb, '[]'::jsonb);
coalesce
----------
[]
(1 row)
最后,正如我从其他评论中看到的,您需要获取 jsonb
的数组长度——有函数 json_array_length(..)
和 jsonb_array_length (..)
专为此目的而设计,请参阅 https://www.postgresql.org/docs/current/static/functions-json.html .
关于postgresql - 在 postgresql 的 array_agg 中将空数组设置为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963496/