在 postgresql 中将空数组设置为 array_agg 的默认值

Ill*_*ian 6 postgresql

我有一个看法:

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;
Run Code Online (Sandbox Code Playgroud)

有时传输为空。如何将空数组设置为 array_agg 的默认值?该字段应该是一个空数组或包含数据的数组。在某些情况下,我使用 array_length 函数来过滤数据。

Nic*_*ick 3

首先,我不会array_agg与 JSON 混合(注意双引号转义;我也使用select array( .. subquery ..)这里使用技巧来获取数组,它在某种程度上相当于你的array_agg(..)):

test=# select array(select '{"zz": 1}'::jsonb);
      array
-----------------
 {"{\"zz\": 1}"}
Run Code Online (Sandbox Code Playgroud)

-- 在这里,您将获得 JSONB 的 ARRAY,而您真正需要的是内部嵌入数组的单个 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)
Run Code Online (Sandbox Code Playgroud)

为了单身jsonb值(内部包含 JSON 数组),请使用jsonb_agg(..)function.

NULL像往常一样,要用某种默认值替换值,您可以使用标准函数coalesce(..)

test=# select coalesce(null::jsonb, '[]'::jsonb);
 coalesce
----------
 []
(1 row)
Run Code Online (Sandbox Code Playgroud)

最后,正如我从其他评论中看到的,您需要获取您的数组长度jsonb- 有一些函数json_array_length(..)jsonb_array_length(..)为此目的而设计,请参阅https://www.postgresql.org/docs/current/static/functions-json.html