如何获取PostgreSQL中数组的最后一个元素? [英] How to get the last element of an array in PostgreSQL?

查看:534
本文介绍了如何获取PostgreSQL中数组的最后一个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于数组的PostgreSQL文档提供了使用<$ c的示例$ c> [-1] 访问似乎是数组的最后一个元素的内容;但是,当 SELECT arr [2:3]; 产生 {5,9} 时, arr [2:-1] 产生 {}

The PostgreSQL Documentation on arrays provides an example using [-1] to access what appears to be the last element of an array; however while SELECT arr[2:3]; produces {5,9}, arr[2:-1] results in {}.

如何在PostgreSQL中获得数组的最后一个元素?

How can the last element of an array be obtained in PostgreSQL?

编辑:Windows,PostgreSQL v9。 2.1

Windows, PostgreSQL v9.2.1

推荐答案

我认为您误解了该示例。 PostgreSQL数组不必从1索引到 n 这只是默认设置

I think you're misinterpreting the example. PostgreSQL arrays don't have to be indexed from 1 to n, that's just the default:


默认情况下,PostgreSQL对数组使用基于1的编号约定,即 n 元素的数组以 array [1] 开头,以 array [n] 。

您正在查看的示例是:

SELECT f1[1][-2][3] AS e1, f1[1][-1][5] AS e2
 FROM (SELECT '[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[] AS f1) AS ss;

但是这些负数并不是像Perl这样的语言从数组末尾开始索引的。在 FROM(SELECT ... 部分,他们指定了起始索引和结束索引,因此 f1 [1] [-1 ] [5] 只是一个普通的旧索引。请考虑以下 array_dims 结果:

But those negative numbers aren't indexing from the end of the arrays as in languages such as Perl. In the FROM (SELECT ... part, they're specifying the starting and ending indexes so the -1 in f1[1][-1][5] is just a plain old index. Consider this array_dims result:

=> SELECT array_dims('[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[]);
    array_dims     
-------------------
 [1:1][-2:-1][3:5]

如果您使用默认的基于1的数组,则可以使用简单的 arr [array_length(arr,1)] 。如果您未使用默认的 [1:n] 数组,您将不得不弄乱 array_lower array_upper 获取第一个和最后一个元素;或者,根据情况,您也许可以使用 unnest 解压缩数组,然后将其作为行集使用。

If you're using the default 1-based arrays then you can get the last element with a simple arr[array_length(arr, 1)]. If you're not using the default [1:n] arrays then you'll have to mess around with array_lower and array_upper to get the first and last elements; or, depending on the circumstances, you might be able to use unnest to unpack the array then work with the array as a rowset.

这篇关于如何获取PostgreSQL中数组的最后一个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆