postgresql – 将表转换为自定义类型数组
发布时间:2020-12-13 15:50:59 所属栏目:百科 来源:网络整理
导读:将一个列表转换为单维数组很容易; my_array integer[];my_array := ARRAY(SELECT * FROM single_column_table); 但在我的情况下,我需要将具有多个列的表转换为自定义类型对象的数组; 所以我有自定义类型 TYPE dbfile AS (fileid integer,deleted boolean,nam
将一个列表转换为单维数组很容易;
my_array integer[]; my_array := ARRAY(SELECT * FROM single_column_table); 但在我的情况下,我需要将具有多个列的表转换为自定义类型对象的数组; 所以我有自定义类型 TYPE dbfile AS (fileid integer,deleted boolean,name text,parentid integer,... ALTER TYPE dbfile 和数组声明为 my_files dbfile[]; -- how to cast table to array of custom types??? my_files := SELECT * FROM get_files(); -- get_files return SETOF dbfile. 如何将表转换为自定义类型数组? ARRAY()不起作用,因为它需要单列. 解决方法
你必须使用ROW构造函数:
postgres=# SELECT * FROM foo; ┌────┬───────┐ │ a │ b │ ╞════╪═══════╡ │ 10 │ Hi │ │ 20 │ Hello │ └────┴───────┘ (2 rows) postgres=# SELECT ARRAY(SELECT ROW(a,b) FROM foo); ┌──────────────────────────┐ │ array │ ╞══════════════════════════╡ │ {"(10,Hi)","(20,Hello)"} │ └──────────────────────────┘ (1 row) 任何PostgreSQL表都有一个名为记录类型表的虚拟列,其中包含与表的列相关的字段.你可以用它: postgres=# SELECT ARRAY(SELECT foo FROM foo); ┌──────────────────────────┐ │ array │ ╞══════════════════════════╡ │ {"(10,Hello)"} │ └──────────────────────────┘ (1 row) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |