Postgres返回多表关联结果集的表函数返回类型如何定义
PostgreSQL多表关联结果的表函数返回类型定义
多表JOIN的结果没有默认注册的数据库类型,PostgreSQL提供了三种常用方案实现返回类型定义:
- 优先推荐:用
RETURNS TABLE显式声明返回列结构
你可以直接在返回类型位置定义所有返回字段的名称和对应类型,适配任意自定义的查询结果结构,示例写法如下,字段定义需替换为你实际查询返回的列名与对应类型:
create or replace function select_from_joined_tables(arg text) returns table ( p_id int, website text, sales_amount numeric, product_name text, product_price numeric ) language sql as $$ select p_id, website, amount, p_name, price from sales join product using (p_id) where website = arg $$;
调用时直接执行select * from select_from_joined_tables('xxx.com');即可。
- 基于已有视图/复合类型定义
如果你提前为该JOIN结果创建了对应视图或者自定义复合类型,可以直接返回该类型的集合:
第一步先创建关联结果对应的视图:
create view sales_product_view as select * from sales join product using (p_id);
函数就可以直接使用视图作为返回类型:
create or replace function select_from_joined_tables(arg text) returns setof sales_product_view language sql as $$ select * from sales join product using (p_id) where website = arg $$;
- 不推荐:用
RETURNS SETOF RECORD
这种方式不需要提前定义返回结构,但调用时必须手动指定列名和类型,使用成本很高,示例调用方式:
select * from select_from_joined_tables('xxx.com') as t(p_id int, website text, amount numeric, p_name text);
如果你要实现问题中提到的三层关联(sales+product+other)的函数,只需要把RETURNS TABLE里的字段定义替换为三层关联后所有返回列的对应类型即可。
内容的提问来源于stack exchange,提问作者David542
相关产品推荐
相关产品推荐

