温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PostgreSQL -- 数组类型操作

发布时间:2020-07-06 18:14:38 来源:网络 阅读:20795 作者:朱飞东 栏目:MySQL数据库

一、数组类型创建表

数组类型,要求数组内的元素属于同一种类型,当出现No function matches the given name and argument types. You might need to add explicit type casts.报错的时候,说明 list 的格式和插入数据或者修改数据的格式不同导致的, 类型很重要,需要保证类型相同才可以操作
 

1.1、建表指定数组类型

只需要在表字段类型后面加'[]'

postgres=# create table test1 (
    id serial, 
    arr int[], 
    name varchar(10)[], 
    age char(10)[], 
    score float[]
    ); 

postgres=# \d+ test1;
                                                 Table "public.test1"
     Column |          Type           |                     Modifiers                      | Storage  | Stats target | Description 
--------+-------------------------+----------------------------------------------------+----------+--------------+-------------
 id     | integer                 | not null default nextval('test1_id_seq'::regclass) | plain    |              | 
 arr    | integer[]               |                                                    | extended |              | 
 name   | character varying(10)[] |                                                    | extended |              | 
 age    | character(10)[]         |                                                    | extended |              | 
 score  | double precision[]      |                                                    | extended |              | 

 

1.2、数据插入

postgres=# insert into test(id, uid) values(3, '{1, 2, 3}');        插入数组方式1
postgres=# insert into test(id, uid) values(3, array[20, 30]::int8[]);   插入数组方式二

1.3、修改数组:

postgres=# update test set uid = uid || '{0}';    后面追加一个数组
postgres=# update test set uid='{0,0}' || uid;   在前面插入一个数组
postgres=# update arr_test set uid=array_append(uid, '1'::int);   指明类型追加一个数
postgres=# update arr_test set uid=array_append(uid, 1);   按默认int类型追加一个数
postgres=# update arr_test set uid=array_prepend('1'::int, uid);     在前面插入一个数

1.4、删除数组中的数据

postgres=# update arr_test set uid=array_remove(uid, '1'::int);  指明类型移除指定的数

1.5、查找数组中的数据

postgres=# select * from test where 20=any(uid);    #uid数组中存在20的row
postgres=# select * from test where uid && array[20, 1]::int8[];   uid数组中和array[20, 1]存在交集的
postgres=# select * from arr_test where uid@>'{1, 2}';   uid 数组中同时包含[1, 2]的
postgres=# select * from arr_test where uid<@'{1, 2}';   uid 数组被[1, 2]包含的

postgres=# select * from arr_test where 2=uid[1]; 使用uid 数组下标查询,下标是从1开始的
postgres=# select id, uid[2] from arr_test; 使用下标显示

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI