create table contacts (
id serial primary key,
name varchar(100),
phones text[]
);
INSERT INTO contacts (name, phones)
VALUES('John Doe',ARRAY [ '(408)-589-5846','(408)-589-5555' ]);
INSERT INTO contacts (name, phones)
VALUES('Lily Bush','{"(408)-589-5841"}'),
('William Gate','{"(408)-589-5842","(408)-589-58423"}');
通过[] 加上下标方式访问数组元素。PostgreSQL 访问数组元素是从1 开始。因此获取第一个电话使用 phone[1]:
select phones[1] from contacts; --(408)-589-5846
select (ARRAY['A','B']::text[])[1]; ---A
SELECT
name,phones[2]
FROM
contacts
WHERE
phones [ 2 ] = '(408)-589-58423';
修改
UPDATE contacts
SET phones = '{(408)-589-5842,(408)-589-58423}'
WHERE ID = 3;
修改
UPDATE contacts
SET phones[3] = '(408)-589-3333'
WHERE ID = 3;
假设我们需要检查phones字段包括特定号码,并不关心是第几个元素,可以使用any() 函数:
SELECT
name,
phones
FROM
contacts
WHERE
'(408)-589-5555' = any (phones)
unnest()函数可以扩展数组为多行,请看示例:
select name,unnest(phones) from contacts
CREATE TABLE city(
country character varying(64),
city character varying(64)
);
INSERT INTO city VALUES
('中国','台北'),
('中国','香港'),
('中国','上海'),
('日本','东京'),
('日本','大阪');
select country,string_agg(city,';' order by city desc) from city group by country
select country,array_agg(city) from city group by country
create table test_array(id int4[]);
INSERT INTO test_array(id) values(array[1,2,4]),(array[4,5,6]);
select array_agg(id) from test_array;
select array_length(id,1),id from test_array --显示一维度长度
select array_to_string(id,’ ‘) from test_array
select array_to_string(array_agg(id),’|') from test_array
select json_array_elements('["T100","SC","BSV"]');
select json_array_elements('[{"name":"zs"},{"name":"lisi"}]');
select json_array_elements_text('[{"name":"zs"},{"name":"lisi"}]')
select json_array_elements_text('[{"name":"zs"},{"name":"lisi"}]')::json ;
select field1 ->>'name' as name from (
select json_array_elements('[{"name":"zs"},{"name":"lisi"}]'::json) as field1
) as t1
json中使用->和->>取值的区别
->> 取值结果类型是文本
-> 取值结果类型是json
select 1
union all
select 1
select 2
except
select 2
select 1
intersect
select 1
select unnest(array[1,2,3])
intersect
select unnest(array[1,2]); ---得到交集
select array_cat(array[1,2],array[2,3]); 不去重
select array[1,2,3] && array[1,2] 返回true,表示有交集
select jsonb_path_query_array('[{"name":"zs","age":"23"},{"name":"lisi","age":"18"}]'::jsonb,'$[*].name');
select jsonb_array_elements_text(jsonb_path_query_array('[{"name":"zs","age":"23"},{"name":"lisi","age":"18"}]'::jsonb,'$[*].name')) ;
select array(select jsonb_array_elements_text(jsonb_path_query_array('[{"name":"zs","age":"23"},{"name":"lisi","age":"18"}]'::jsonb,'$[*].name')) )
select unnest (array(select jsonb_array_elements_text(jsonb_path_query_array('[{"name":"zs","age":"23"},{"name":"lisi","age":"18"}]'::jsonb,'$[*].name'))) )
select array(
select 'A' union all
select 'B' union all
select 'C'
) ;
select array_to_string(array(
select 'A' union all
select 'B' union all
select 'C'
) ,'~~') ;
SELECT jsonb_path_query_array(
'[1, 2, 3, 4]',
'$[*] ? (@ >= $min && @ <= $max)',
'{"min": 2, "max": 3}'
);