Postgres支持表的字段使用定长或可变长度的一维或多维数组,数组的类型可以是任何数据库内建的类型、用户自定义的类型、枚举类型以及组合类型。
举个例子:
create table ta(id int, col int[]);
从上面的例子中可以看出,数组类型的定义就是通过在数组元素类型后面附加"[]"来实现的。方括号中可以给一个长度数字,也可以不给,这个长度数字是无效的,不会限制数组长度。
我们继续看一下如何输入数组值:
postgres=# insert into ta values (1,'{1,2,3}');
INSERT 0 1
postgres=# insert into ta values (2,'{2,4,6}');
INSERT 0 1
postgres=# select * from ta;
id | col
----+---------
1 | {1,2,3}
2 | {2,4,6}
(2 rows)
默认情况下数据库中数组的下标是从1开始的,访问数组的示例如下:
postgres=# select id,col[1] from ta;
id | col
----+-----
1 | 1
2 | 2
(2 rows)
postgres=# select id,col[1],col[2],col[3] from ta;
id | col | col | col
----+-----+-----+-----
1 | 1 | 2 | 3
2 | 2 | 4 | 6
(2 rows)
我们继续看一下数组的函数,有很多数组函数,比如unnest(anyarray):
postgres@postgres=# select unnest(array[1,2,3]);
unnest
--------
1
2
3
(3 rows)
postgres@postgres=# select array[1,2,3];
array
---------
{1,2,3}
(1 row)
最后修改时间:2023-11-02 22:29:29
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




