如何在 PostgreSQL 中获取数组的最后一个元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12765955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the last element of an array in PostgreSQL?
提问by mu is too short
The PostgreSQL Documentation on arraysprovides 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 文档提供了一个示例,[-1]
用于访问似乎是数组最后一个元素的内容;然而,虽然SELECT arr[2:3];
产生{5,9}
,arr[2:-1]
结果{}
。
How can the last element of an array be obtained in PostgreSQL?
PostgreSQL 中如何获取数组的最后一个元素?
Edit: Windows, PostgreSQL v9.2.1
编辑:Windows、PostgreSQL v9.2.1
回答by Abhishek Jain
For any array "arr", to fetch the last element of array arr use
对于任何数组“arr”,要获取数组 arr 的最后一个元素,请使用
SELECT arr[array_upper(arr, 1)];
回答by mu is too short
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
,这只是默认值:
By default PostgreSQL uses a one-based numbering convention for arrays, that is, an array of nelements starts with
array[1]
and ends witharray[n]
.
默认情况下,PostgreSQL 对数组使用基于 1 的编号约定,即n 个元素的数组以开头
array[1]
并以 结尾array[n]
。
The example you're looking at is this:
您正在查看的示例是:
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;
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:
但是这些负数不像在 Perl 之类的语言中那样从数组的末尾开始索引。在这FROM (SELECT ...
部分中,他们指定了起始索引和结束索引,因此 -1 inf1[1][-1][5]
只是一个普通的旧索引。考虑这个array_dims
结果:
=> SELECT array_dims('[1:1][-2:-1][3:5]={{{1,2,3},{4,5,6}}}'::int[]);
array_dims
-------------------
[1:1][-2:-1][3:5]
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.
如果您使用默认的基于 1 的数组,那么您可以使用简单的arr[array_length(arr, 1)]
. 如果您没有使用默认[1:n]
数组,那么您将不得不处理array_lower
并array_upper
获取第一个和最后一个元素;或者,根据情况,您可以使用unnest
解包数组,然后将数组作为行集处理。