天天看点

postgresql 数组类型

 --pg支持数组,且支持分片访问,比如[1:2],任意只有一个数字(没有冒号)的维数是从 1 开始到声明的数字为止的

 --如果任意维数被写为一个片段,也就是,包含一个冒号,那么所有维数都被当做是片段

if any dimension is written as a slice, i.e., contains a colon, then all dimensions are treated as slices. 

any dimension that has only a single number (no colon) is treated as being from 1 to the number specified. 

for example, [2] is treated as [1:2], as in this example:

select schedule[1:2][2] from sal_emp where name = 'bill';

--任何数组的当前维数都可以用 array_dims 函数检索:

select array_dims(schedule) from sal_emp where name = 'carol';

array_dims

------------

[1:2][1:2]

--也可以用 array_upper 和 array_lower 函数分别返回数组特定维的上界和下界:

select array_upper(schedule, 1) from sal_emp where name = 'carol'

--如果数组本身或任何下标表达式是 null ,那么该数组的下标表达式也将生null 。 从一个数组的当前范围之外抓取数据将生成一个 null ,而不是导致错误 

--array_length可用于返回指定维数的长充

select array_length(schedule, 1) from sal_emp where name = 'carol';

array_length

--------------

2

--cardinality 返回任意维数的元素个数

--cardinality returns the total number of elements in an array across all dimensions. it is effectively the number of rows a call to unnest would yield:

select cardinality(schedule) from sal_emp where name = 'carol';

cardinality

-------------

4

--更新指定索引的数组值

update sal_emp set pay_by_quarter[4] = 15000 where name = 'bill';

--更新指定分片的数组值

update sal_emp set pay_by_quarter[1:2] = '{27000,27000}' where name = 'carol';

--可以通过给一个尚不存在数组元素赋值的办法扩大数组, 所有位于原数组最后一个元素和这个新元素之间的未赋值元素都将设为 null 。 

--例如,如果 myarray数组当前有 4 个元素, 在对 myarray[6]赋值之后它将拥有 6 个元素,其中myarray[5] 的值将为 null

--检索数组中是否包含任一元素,或者包含所有的元素

select * from sal_emp where 10000 = any (pay_by_quarter);

select * from sal_emp where 10000 = all (pay_by_quarter);

--检索数组包含元素的索引,注意第一个函数匹配第一次满足条件的,第二个函数匹配所有的满足条件的

select array_position(array['sun','mon','tue','wed','thu','fri','sat','mon'], 'mon'),array_positions(array[1, 4, 3, 1, 3, 4, 2, 1], 1);

 array_position | array_positions 

----------------+-----------------

              2 | {1,4,8}

--数组运算中的一些比较符

运算符                  描述

a = b                   立方体a和b是相同的

a && b                  立方体a和b重叠

a @> b                  立方体a包含立方体b

a <@ b                  立方体a被包含在立方体b中

[a, b] < [c, d]         小于

[a, b] > [c, d]         大于

postgres=# select array[1,2,3],array[2,3,4];

  array  |  array  

---------+---------

 {1,2,3} | {2,3,4}

--两个群组中是否有重叠 

postgres=# select array[1,2,3]&&array[2,3,4];

 ?column? 

----------

 t

--第一个数组是否包含第二个数组

postgres=# select array[1,2,3]@>array[2,3,4];

 f

postgres=# select array[1,2,3]@>array[2,3];  

--第一个数组是否被第二个数组包含 

postgres=# select array[1,2,3]<@array[2,3];

postgres=# select array[1,2,3]<@array[1,2,3,4];

(1 row)