通过在postgres中使用连接来获取函数中不同表的多列

时间:2014-12-08 18:53:47

标签: postgresql

以下是包含表格名称' company'

的表格的示例
id     name          age         address
1      Paul          32          California  

Ans第二个表名"部门"

id     dept_name       dept_id 
1      engineering       5

从上表中我是否通过组合id列并检索字段作为名称,年龄,地址,部门进行连接。

我在这里做的是: -

create type tmp_comp as(name text,age integer, address character, dept character);

create or replace function comp_detail (in_id integer)
returns tmp_comp as
$$

declare 
out_put tmp_comp%rowtype;

begin
select name, age, address,dept from company as c inner join department as d on c.id=d.id where c.id=in_id;
return out_put;
end;$$
LANGUAGE plpgsql 

如果我执行此操作,它将会成功。

但如果我想调用该函数,则会显示错误...

select * from comp_detail(1)


ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead.
CONTEXT:  PL/pgSQL function comp_detail(integer) line 7 at SQL statement

1 个答案:

答案 0 :(得分:0)

您可以使用RETURN QUERY按照here

所述返回SETOF A_TYPE
create or replace function comp_detail (in_id integer) returns setof tmp_comp as $$

declare out_put tmp_comp%rowtype;

begin 
    return query(select name, age, address,dept from company as c inner join department as d on c.id=d.id where c.id=in_id);
end;$$

LANGUAGE plpgsql

您可以按照以下方式调用您的函数:

select * from comp_detail (1);