Postgres 中的多维数组支持非常具体。不存在多维数组类型。如果将数组声明为多维数组,Postgres 会自动将其转换为简单数组类型:
create table test(a integer[][]);
\d test
Table "public.test"
Column | Type | Modifiers
--------+-----------+-----------
a | integer[] |
您可以将不同维度的数组存储在数组类型的列中:
insert into test values
(array[1,2]),
(array[array[1,2], array[3,4]]);
select a, a[1] a1, a[2] a2, a[1][1] a11, a[2][2] a22
from test;
a | a1 | a2 | a11 | a22
---------------+----+----+-----+-----
{1,2} | 1 | 2 | |
{{1,2},{3,4}} | | | 1 | 4
(2 rows)
这是 Postgres 与 C、python 等编程语言之间的关键区别。该功能有其优点和缺点,但通常会给新手带来各种问题。
可以在系统目录pg_attribute中找到维数:
select attname, typname, attndims
from pg_class c
join pg_attribute a on c.oid = attrelid
join pg_type t on t.oid = atttypid
where relname = 'test'
and attnum > 0;
attname | typname | attndims
---------+---------+----------
a | _int4 | 2
(1 row)
不清楚你是否可以依赖这个号码,至于the documentation:
attndims - 维数,如果列是数组类型;否则为 0。(目前,数组的维数未强制执行,因此任何非零值实际上都意味着“它是一个数组”。)