加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL学习篇9.17 数组类型

发布时间:2020-12-13 16:59:07 所属栏目:百科 来源:网络整理
导读:数组类型声明:create table testsz(id int,col1 int[]);输入数组值:postgres=# create table testsz(id int,col1 int[]);CREATE TABLEpostgres=# insert into testsz values(1,'{1,2,3}');INSERT 0 1postgres=# insert into testsz values(2,'{4,5,3}');IN
数组类型声明:
create table testsz(id int,col1 int[]);

输入数组值:
postgres=# create table testsz(id int,col1 int[]);
CREATE TABLE
postgres=# insert into testsz values(1,'{1,2,3}');
INSERT 0 1
postgres=# insert into testsz values(2,'{4,5,3}');
INSERT 0 1
postgres=# select * from testsz;
 id |  col1   
----+---------
  1 | {1,3}
  2 | {4,3}
(2 rows)

postgres=#

数组访问:
postgres=# select id,col1[1] from testsz;
 id | col1
----+------
  1 |    1
  2 |    4
(2 rows)

postgres=#

数组值修改:
postgres=# select * from testsz;
 id |  col1   
----+---------
  1 | {1,3}
(2 rows)

postgres=# update testsz set col1='{9,11,13}' where id=1;
UPDATE 1
postgres=# select * from testsz;
 id |   col1   
----+-----------
  2 | {4,3}
  1 | {9,13}
(2 rows)

postgres=# update testsz set col1[3]=19 where id=1;
UPDATE 1
postgres=# select * from testsz;
 id |   col1   
----+-----------
  2 | {4,19}
(2 rows)

postgres=#

重点介绍两个函数:
unnest(anyarray):把数组变成多行返回;
array_agg():数组聚合

示例:、
postgres=# create table testfun(id int,v int);
CREATE TABLE
postgres=# insert into testfun values(1,1);
INSERT 0 1
postgres=# insert into testfun values(1,2);
INSERT 0 1
postgres=# insert into testfun values(1,3);
INSERT 0 1
postgres=# insert into testfun values(2,1);
INSERT 0 1
postgres=# insert into testfun values(2,2);
INSERT 0 1
postgres=# insert into testfun values(2,3);
INSERT 0 1
postgres=# insert into testfun values(3,5);
INSERT 0 1
postgres=# select * from testfun;
 id | v
----+---
  1 | 1
  1 | 2
  1 | 3
  2 | 3
  2 | 1
  2 | 2
  2 | 3
  3 | 3
  3 | 5
(9 rows)

postgres=# select id,array_agg(v) from testfun group by id;
 id | array_agg
----+-----------
  1 | {1,3}
  3 | {3,5}
  2 | {3,1,3}
(3 rows)

postgres=# select * from testsz;
 id |   col1   
----+-----------
  2 | {4,19}
(2 rows)

postgres=# select id,unnest(col1) from testsz;
 id | unnest
----+--------
  2 |      4
  2 |      5
  2 |      3
  1 |      9
  1 |     11
  1 |     19
(6 rows)

postgres=#




 
 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读