一、数组类型创建表

数组类型,要求数组内的元素属于同一种类型,当出现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; 使用下标显示