数组
在 PostgreSQL 中,你可以创建任何内置,用户定义或枚举类型的数组。默认情况下,Array 没有限制,但你可以指定它。
声明一个数组
SELECT integer[];
SELECT integer[3];
SELECT integer[][];
SELECT integer[3][3];
SELECT integer ARRAY;
SELECT integer ARRAY[3];
创建一个数组
SELECT '{0,1,2}';
SELECT '{{0,1},{1,2}}';
SELECT ARRAY[0,1,2];
SELECT ARRAY[ARRAY[0,1],ARRAY[1,2]];
访问阵列
默认情况下,PostgreSQL 对数组使用一种基于编号的约定,即 n 个元素的数组以 array[1]
开头,以 array[n]
结尾。
--accesing a spefific element
WITH arr AS (SELECT ARRAY[0,1,2] int_arr) SELECT int_arr[1] FROM arr;
int_arr 0
(1 row)
--sclicing an array
WITH arr AS (SELECT ARRAY[0,1,2] int_arr) SELECT int_arr[1:2] FROM arr;
int_arr {0,1}
(1 row)
获取有关阵列的信息
--array dimensions (as text)
with arr as (select ARRAY[0,1,2] int_arr) select array_dims(int_arr) from arr;
array_dims [1:3]
(1 row)
--length of an array dimension
WITH arr AS (SELECT ARRAY[0,1,2] int_arr) SELECT array_length(int_arr,1) FROM arr;
array_length
--------------
3
(1 row)
--total number of elements across all dimensions
WITH arr AS (SELECT ARRAY[0,1,2] int_arr) SELECT cardinality(int_arr) FROM arr;
cardinality
-------------
3
(1 row)
数组函数
将被添加