导读 这篇文章主要介绍了解决PostgreSQL Array使用中的一些小问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在PostgreSQL 中可以使用Array数据结构,例如

select array[1,2,3]; 
return {1,2,3}

但是,如果

select array[1,2,3][1]; --会报错 
select (select array[1,2,3])[1] --可以使用

那么在用正则匹配函数 regexp_match 就会遇到这样的问题,如

select regexp_match('123-123', '(\d+)-(\d+)'); --return {123, 123}
select regexp_match('123-123', '(\d+)-(\d+)')[1]; --报错

但是,如果你想获取其中一个元素,你就得使用嵌套查询,如

select(select regexp_match('123-123', '(\d+)-(\d+)'))[1]; --return 123

其次,你如果要用regexp_matches 加上全局搜索,可能会生成多行数据,如

select 'a', array(select regexp_matches('aa-aa', '(aa)+', 'g'));
-- return 2 rows
a {aa}
a {aa}

合并为一行,需要array函数

select 'a', array(select regexp_matches('aa-aa', '(aa)+', 'g'));
--return 
a {{aa},{aa}}

取其中的元素

select a, b[1][1] from (select 'a' as a, array(select regexp_matches('aa-aa', '(aa)+', 'g')) as b) as c;
--return 
aa
补充:PostgreSQL的 array_to_string 功能

开始

用 第二个参数连接数组元素,例:

postgres=# select array_to_string (ARRAY[1,2,3],'##');
 array_to_string 
-----------------
 1##2##3
(1 row)
postgres=# 

结束~

以上为个人经验,希望能给大家一个参考。

原文来自:https://www.jb51.net/article/204877.htm

本文地址:https://www.linuxprobe.com/postgresql-array-linux.html编辑:向金平,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/