sql - 从 json[] 中删除了最后一个元素?

标签 sql arrays postgresql postgresql-9.4

我在 PostgreSQL 9.4 中有一个 json[] 数组 (_result_group),我想删除它的最后一个 json 元素 (_current)。我准备了:

_result_group := (SELECT array_append(_result_group,_current));

并尝试删除:

SELECT _result_group[1:array_length(_result_group,1) -1] INTO _result_group;

但是没有用。
如何做到这一点?

最佳答案

要使用 Postgres 9.4 的方法从 任何 数组(包括 json[])中删除 last 元素,显然在 plpgsql 代码中:

_result_group := _result_group[1:cardinality(_result_group)-1];

假设一个一维数组,默认下标以 1 开头。

对于空数组输入,您会得到一个空数组,对于 null,您会得到 null。

根据 the manual , 基数() ...

returns the total number of elements in the array, or 0 if the array is empty

然后只需将数组切片从 1 到基数 -1。

话又说回来,你的尝试也应该奏效:

SELECT _result_group[1:array_length(_result_group,1) -1] INTO _result_group;

对于非标准数组下标,请参见:

关于sql - 从 json[] 中删除了最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58512894/

相关文章:

c - 如何在 C 中打印一个数组覆盖另一个数组?

arrays - 将元素添加到新数组 Ruby

sql - 为性能选择索引和主键

postgresql - 查找 MAX(db timestamp) 查询

mysql - 忽略where子句sql中的某些列

sql - 选择在 <x 天的时间段内重复出现

带有 OR 的 javascript 数组声明

sql - PostgreSQL 聚合 View

sql - 如何从 SQL SSIS 中的日期时间字符串中去除日期?

sql - 如何使用 Oracle SQL 向 rank() 添加移动窗口