【问题标题】:How to return an array of table records in PostgreSQL如何在 PostgreSQL 中返回表记录数组
【发布时间】:2020-08-21 14:30:00
【问题描述】:

我在尝试返回 table1 类型的元素数组时遇到类型不匹配错误,这是我声明的 table1 的固有类型。

Error occurred during SQL query execution

Razón:
 SQL Error [42P13]: ERROR: return type mismatch in function declared to return table1[]
  Detail: Actual return type is record[].
  Where: SQL function "arrayof_records"

这是重现我的问题的过度简化的代码。

drop table if exists table1 cascade;

create table table1 (
  id        serial primary key,
  title     text,
  create_dt timestamp default now()
);

insert into table1 (title) values 
('one'),
('two'),
('three');

create or replace function arrayof_records ()
returns table1[]
stable language sql as $$
  select array_agg (t.*)
  from (
    select * from table1
    order by create_dt desc
  ) as t;
$$;

很明显,解析器期待array_agg 函数中的其他表达式。我试过tt.**。都失败了。

我希望有一个语法,因为 PostgreSQL 12 文档声明“array_agg(expression)|any non-array type”。

有什么想法吗?

【问题讨论】:

  • array_agg(t)?但是为什么要返回一个数组呢?为什么不使用returns setof table1
  • 不,我测试过:`SQL 查询执行期间发生错误 Razón:SQL 错误 [42P13]:错误:在声明返回 table1[] 的函数中返回类型不匹配详细信息:实际返回类型是记录 [ ]。其中:SQL 函数“arrayof_records”``
  • 看来我必须输入演员表?
  • 右:t::table1
  • 谢谢@a_horse_with_no_name

标签: postgresql postgresql-12 array-agg


【解决方案1】:

您可以使用稍微不同的方式来创建数组:

create or replace function arrayof_records ()
  returns table1[]
  stable language sql 
as 
$$
  select array(
    select table1 
    from table1
    order by create_dt desc
  );
$$;

这通常也比 array_agg() 快。

【讨论】:

  • 谢谢,速度对我来说很重要。
猜你喜欢
  • 1970-01-01
  • 2019-02-14
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
  • 2017-01-02
  • 1970-01-01
相关资源
最近更新 更多