简体   繁体   English

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

[英]How to get the last element of an array in PostgreSQL?

The PostgreSQL Documentation on arrays provides an example using [-1] to access what appears to be the last element of an array; PostgreSQL 数组文档提供了一个使用[-1]访问数组最后一个元素的示例; however while SELECT arr[2:3];然而当SELECT arr[2:3]; produces {5,9} , arr[2:-1] results in {} .产生{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

对于任何数组“arr”,要获取数组 arr 的最后一个元素,请使用

SELECT arr[array_upper(arr, 1)];

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 n elements starts with array[1] and ends with array[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.但是这些负数不像在 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:FROM (SELECT ...部分,他们指定了开始和结束索引,所以f1[1][-1][5]的 -1 只是一个普通的旧索引。考虑这个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)] .如果您使用默认的基于 1 的数组,那么您可以使用简单的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;如果您没有使用默认的[1:n]数组,那么您将不得不使用array_lowerarray_upper来获取第一个和最后一个元素; or, depending on the circumstances, you might be able to use unnest to unpack the array then work with the array as a rowset.或者,根据情况,您可以使用unnest来解包数组,然后将数组作为行集处理。

If someone is using Postgre 9.5, the documentation says:如果有人使用 Postgre 9.5,文档说:

-> int

Get JSON array element (indexed from zero, negative integers count from the end)获取 JSON 数组元素(从零开始索引,负整数从末尾开始计数)

So this works for me:所以这对我有用:

to_json(arr)->-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM