首页 > 解决方案 > 用作查询变量以返回结果的函数

问题描述

基本上我需要为网站人员创建一个函数来调用查询搜索,他输入一个 id,我需要从与该 id 相交的其他表中返回一些 id

我的功能是(不起作用)

create or replace function return_id (id integer) 
 returns table (derpid integer, object text)
as $function$
begin
RETURN QUERY
select x.objectid, x.object_class 
from (
select objectid, object_class from table1 a where st_intersects(a.geom, (select geometry from searchtable where id = $1) ) and st_length(st_intersection(a.geom, (select geometry from ftth.cable where id = $1))) > 1 
) x ;
end;
$function$ language plpgsql VOLATILE
COST 100;

这个想法是让 $1 成为用户想要搜索的变量。我需要返回对象 ID 和对象类,但不断遇到错误

ERROR: column reference "id" is ambiguous
Detail: It could refer to either a PL/pgSQL variable or a table column.

如何使这项工作?

标签: sqlpostgresqlfunction

解决方案


重命名参数的首选方式:

create or replace function return_id (p_id integer) 
  returns table (derpid integer, object text)
as $function$
  select x.objectid, x.object_class 
  from (
    select objectid, object_class 
    from table1 a 
    where st_intersects(a.geom, (select geometry from searchtable where id = p_id) ) 
      and st_length(st_intersection(a.geom, (select geometry from ftth.cable where id = p_id))) > 1 
  ) x ;
$function$ 
language sql
stable;

另一种方法是限定列引用(例如,通过使用表别名):

create or replace function return_id (id integer) 
  returns table (derpid integer, object text)
as $function$
  select x.objectid, x.object_class 
  from (
    select objectid, object_class 
    from table1 a 
    where st_intersects(a.geom, (select geometry from searchtable st where st.id = $1) ) 
      and st_length(st_intersection(a.geom, (select geometry from ftth.cable c where c.id = $1))) > 1 
  ) x ;
$function$ 
language sql
stable;

请注意,我还更改了language sql对于包装查询的简单函数通常更有效的函数。


推荐阅读