You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL存储函数返回唯一整数数组时出现结果类型不匹配错误求助

解决PostgreSQL存储函数返回唯一整数值数组的问题

问题原因分析

  • SQL语句里误用了关键字table作为表名,应替换为实际表名my_table
  • 函数定义的返回类型是table ("entry_id" int),和你需要返回数组的需求不匹配,同时错误的表名引用也会触发结构不匹配报错

方案1:修正返回表结构的函数(若仍需返回表)

如果只是想修复当前返回表的报错,修改表名引用即可:

create or replace function get_unique_entries(id int)
   returns table ("entry_id" int)
language plpgsql
as
$$
begin
   return query  
      select distinct my_table.entry_id  -- 修正表名为my_table
      from my_table 
      where x = id;
end;
$$;

调用方式:

select * from get_unique_entries(2);

方案2:修改函数返回整数数组(满足核心需求)

若要返回唯一整数值的数组,需调整返回类型为int[],并用聚合函数处理结果:

PL/pgSQL版本

create or replace function get_unique_entries(id int)
   returns int[]
language plpgsql
as
$$
begin
   return array(
      select distinct my_table.entry_id 
      from my_table 
      where x = id
   );
end;
$$;

更简洁的纯SQL版本

create or replace function get_unique_entries(id int)
   returns int[]
language sql
as
$$
   select array_agg(distinct entry_id)
   from my_table 
   where x = id;
$$;

调用方式:

select get_unique_entries(2);

执行后会直接返回包含唯一entry_id的整数数组。

内容的提问来源于stack exchange,提问作者Thomas K.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:01:14