【问题标题】:PostgreSQL strange behaviour with array_to_jsonPostgreSQL 与 array_to_json 的奇怪行为
【发布时间】:2021-10-30 07:11:53
【问题描述】:

我想在转换为 JSON 之前使用 array_agg 消除空值,但空值重新出现在 JSON 输出中。 这是一个演示行为的最小示例:

select id, array_agg(alias), array_to_json(array_agg(alias))
from (values (1, 'foo'), (1, 'bar'), (2, null)) t(id, alias)
group by id;

结果集是这样的:

id|array_agg|array_to_json|
--+---------+-------------+
 1|{foo,bar}|["foo","bar"]|
 2|{}       |[null]       |

【问题讨论】:

  • 你可以使用jsonb_agg(alias) filter (where alias is not null)
  • 请注意,array_agg 不会(或不应该)删除 null 值。在运行它之前尝试运行\pset null (null) 以查看空值。
  • 为什么不使用`WHERE alias NOTNULL`?
  • 通常空值将来自左连接,我想要一个空数组用于连接表中没有匹配的 ID,WHERE alias not null 将完全删除行。

标签: sql arrays json postgresql postgresql-13


【解决方案1】:

array_agg 的文档声明它“将所有输入值(包括空值)收集到一个数组中”。显示为空的数组只是输出的格式,但实际上它仍然包含nullhttps://www.postgresql.org/docs/current/functions-aggregate.html

要为null 值获取一个空数组,请使用带有filter 子句和coalescejson_agg

select 
  id,
  coalesce(json_agg(alias) filter (where alias is not null), '[]'::json)
from (values (1, 'foo'), (1, 'bar'), (2, null)) t(id, alias)
group by id;

【讨论】:

    猜你喜欢
    • 2021-01-17
    • 2012-02-02
    • 2017-07-03
    • 2018-03-14
    • 2012-01-19
    • 2022-01-20
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多