【问题标题】:Postgres coalesce to empty JSONB arrayPostgres 合并为空 JSONB 数组
【发布时间】:2017-05-02 20:32:54
【问题描述】:

如何将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

【问题讨论】:

  • 这真的取决于null_column 的确切定义、其中允许的数据以及您的Postgres 版本。

标签: sql arrays postgresql coalesce jsonb


【解决方案1】:

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

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

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

【讨论】:

  • 这很好用,但由于某些奇怪的原因,如果我使用列名而不是 null,我仍然会得到 cannot extract elements from a scalar
  • @norbertpy 忘记解决这个问题 - 您必须将列值转换为 json 数组,因为合并中的两个参数都必须返回 json 数组
  • 我的专栏肯定是 JSONB,但似乎 Postgres 无法判断它为空。甚至这个SELECT (CASE WHEN col IS NULL THEN 'is-null' ELSE 'is-not-null' END) AS r FROM t WHERE id = 13; 也会返回is-not-null
  • 但这将是另一个问题。感谢您的投入。
  • @norbertpy 你确定 col 应该是 null 而不是在 json 中表示 null 的字符串吗?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2021-11-03
    • 2020-11-16
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多