--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)