postgresql 数组类型初步实践
发布时间:2020-12-13 17:14:25 所属栏目:百科 来源:网络整理
导读:实践环境 数据库:postgresql 9.4;操作系统:windows 创建包含数组类型的数据库 注意在设置default 值时(当然你可以不指定默认值),要声明数组的类型,像这样声明"::bigint[]"。 create table testarray(id serial primary key,images bigint[] default a
实践环境数据库:postgresql 9.4;操作系统:windows 创建包含数组类型的数据库注意在设置default 值时(当然你可以不指定默认值),要声明数组的类型,像这样声明"::bigint[]"。 create table testarray( id serial primary key,images bigint[] default array[]::bigint[] ); 插入数组值注意插入数组时,也要声明数组的类型,同上 insert into testarray (images) values(array[1,2,3,4,5,6]::bigint[]); 查询刚插入的数据查询语句: select * from testarray; 结果:
数组的操作判断元素是否存在(操作符:"any")要注意为查询出来的数组指定类型。 select 0 = any ((select images from testarray where id=1)::int[]) as isContain 查询结果:
删除元素(array_romeve),但不影响持久数据select array_remove((select images from testarray)::varchar[],'1'); 查询结果:
删除元素,保存结果思路是将数据查询出来进行操作之后("||"是一个数组操作符,合并元素和数组),再保存回到数据库。可以删除单个元素,也可以删除一个元素集(另一个数组),举一反三。 update testarray set images = (select images from testarray where id=1)::int[] || 1; select images from testarray;
给数据添加元素(操作符:"||"),但是不保存给数组添加元素实际上就是将元素合并到一个数组里,办法很多,这里只距离"||"操作符的使用。 单个元素添加到数组select (select images from testarray where id=1)::int[] || 100 as newimages;
添加多个元素到数组select (select images from testarray where id=1)::int[] || array[200,300,400]::int[] as newimages;
给数据添加元素,并且保存思路同5.3 update testarray update set images = (select images from testarray where id=1)::int[] || array[200,400]::int[] ; select images from testarray;
附录本博客不是系统的教程,只是简单的介绍postgresql 数据类型的使用。关于postgresql数组类型的操作符和函数,可以参见官方文档:http://www.postgresql.org/docs/9.1/static/functions-array.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |