Postgres 中的数组在所有维度上共享相同的基本元素。
匿名记录数组
您可以构建匿名记录数组(作为基本类型):
SELECT array_agg((i,d))
FROM (
VALUES
(1::int, 2.3::decimal)
,(2, 3.4)
,(3, 4.5)
) x(i, d);
但这相当笨重,因为您无法按名称访问匿名记录的子字段(名称不存在!)。与众所周知的类型一起操作可能更实用..
复合类型作为基本类型
创建一个复合类型并将其用作数组的基类型。
CREATE TYPE int_dec AS (i int, d decimal);
SELECT '(1, 2.3)'::int_dec AS id_base
,'{"(1, 2.3)","(2, 3.4)","(3, 4.5)"}'::int_dec[] AS id_arr
-- Build an array from composite base type
SELECT array_agg(a)
FROM (
VALUES
('(1, 2.3)'::int_dec)
,('(2, 3.4)'::int_dec)
,('(3, 4.5)'::int_dec)
) x(a);
-- Build an array from composite base type
SELECT array_agg((i,d)) AS anonymous_arr
,array_agg((i,d)::int_dec) AS id_arr
FROM (
VALUES
(1::int, 2.3::decimal)
,(2, 3.4)
,(3, 4.5)
) x(i, d);
表作为基本类型
Any table可以作为复合类型。
db=# CREATE TEMP TABLE int_dec (i int, d decimal);
CREATE TABLE
db=# INSERT INTO int_dec VALUES (1, 2.3), (2, 3.4), (3, 4.5);
INSERT 0 3
db=# SELECT array_agg(id) FROM int_dec id;
array_agg
---------------------------------
{"(1,2.3)","(2,3.4)","(3,4.5)"}
Text
作为共同点
另一种方法是将所有值转换为text
since every数据类型可以转换为text
返回 PostgreSQL 并构建一个multi-dimensional array
.
为此,您可能有兴趣聚合多维的数组。考虑这个相关问题下的答案:
选择数据到 Postgres 数组中 https://stackoverflow.com/questions/11762398/selecting-data-into-a-postgres-array-format
不过,根据我的经验,通常有比构建复杂数组更好的解决方案。