Postgres 合并为空的 JSONB 数组

Postgres coalesce to empty JSONB array

我怎样才能 coalesce 一个 null 列到一个空的 JSONB 数组中?这不起作用:

SELECT jsonb_array_elements(coalesce(null_column, '{}'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from an object

这都不是:

SELECT jsonb_array_elements(coalesce(null_column, '[]'::jsonb))
FROM table
WHERE id = 13;

-- ERROR:  cannot extract elements from a scalar

{} 是一个对象,但 jsonb_array_elements 需要一个数组,因此将 {} 替换为 []

确保两个参数 return 都是一个 jsonb 数组。例如,如果您的列是整数,则可以使用 concat 添加方括号并使用 ::jsonb 进行转换

SELECT jsonb_array_elements(coalesce(concat('[',my_column,']')::jsonb,'[]'::jsonb))

这里是 SQL 完成你想要的代码:

SELECT jsonb_array_elements(coalesce(null_column, '[{}]'::jsonb))
FROM table
WHERE id = 13;