pg数组类型

2023-03-11,,

数据库版本

postgres=# SELECT version();
version----------------------------------------------------------------------------------------------------------
PostgreSQL 9.6.0 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44), 64-bit
(1 row)

1,创建表

postgres=# CREATE TABLE test_array1(id int,array_i int[],arrat_t text[]);
CREATE TABLE

数组类型插入

postgres=# SELECT '{1,2,3}',array[1,2,3];
?column? | array
----------+---------
{1,2,3} | {1,2,3}
(1 row)
postgres=# INSERT INTO test_array1 values(1,'{1,2,3}','{a,b,c}');
INSERT 0 1
postgres=# INSERT INTO test_array1 values(2,array[1,2,3],array['a','b','c']);
INSERT 0 1

查询数组类型

postgres=# SELECT array_i,arrat_t FROM test_array1;
array_i | arrat_t
---------+---------
{1,2,3} | {a,b,c} {1,2,3} | {a,b,c}
(2 rows)
postgres=# SELECT array_i[1],arrat_t[3] FROM test_array1;
array_i | arrat_t
---------+---------
1 | c 1 | c
(2 rows)

2,数组元素的追加、删除、更新

追加

postgres=# SELECT ARRAY_APPEND(array[1,2,3],4);
array_append
--------------
{1,2,3,4}
(1 row)
postgres=# SELECT array[1,2,3]||4;
?column?
-----------
{1,2,3,4}
(1 row)

删除

postgres=# SELECT ARRAY_REMOVE(ARRAY[1,1,2,3],1);
array_remove
--------------
{2,3}
(1 row)

修改

postgres=# UPDATE test_array1 SET array_i[2] = 1 WHERE id = 1;
UPDATE 1
postgres=# UPDATE test_array1 SET array_i = array[1,2,4] WHERE id = 2;
UPDATE 1

3,数组操作符

postgres=# SELECT ARRAY[1.1,2.2,3.2]::int[] = array[1,2,3];--等于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,3] != array[1,2,4];--不等于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,4] > array[1,2,3];--大于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,3] < array[1,2,4];--小于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,4] >= array[1,2,3];--大于或等于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,3] <= array[1,2,4];--小于或等于
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2,3] @> array[1,2];--包含
?column?
----------
t
(1 row)
postgres=# SELECT ARRAY[1,2] <@ array[1,2,3];--被包含
?column?
----------
t
(1 row)
postgres=# SELECT array[1,2]||array[3,4];--串联
?column?
----------- {1,2,3,4}
(1 row)
postgres=# SELECT array[1,2]||array[[3,4],[5,6]];--串联
?column?
---------------------
{{1,2},{3,4},{5,6}}
(1 row)

4,数组函数

获取数组维度

postgres=# SELECT ARRAY_NDIMS(ARRAY[1,2,3]);
array_ndims
-------------
1
(1 row)

获取数组长度

postgres=# SELECT ARRAY_LENGTH(ARRAY[1,2,3],1);
array_length
--------------
3
(1 row)

返回数组元素第一次出现的位置

postgres=# SELECT ARRAY_POSITION(ARRAY[1,1,2,3],2);
array_position
----------------
3
(1 row)

替换数组中的相同组元素

postgres=# SELECT ARRAY_REPLACE(ARRAY[1,1,2],1,2); array_replace
---------------
{2,2,2}
(1 row)

将数组输出到字符串

postgres=# SELECT ARRAY_TO_STRING(ARRAY['a','b',null,'c'],',','5');--null转为后面指定字符
array_to_string
-----------------
a,b,5,c
(1 row)

pg数组类型的相关教程结束。

《pg数组类型.doc》

下载本文的Word格式文档,以方便收藏与打印。