我希望有一个返回表的函数。我知道用户可以像使用表一样在选择和连接中使用函数调用。但是,select/join是否能够使用函数表返回的源表的索引?
例如:"select id from permitted_resources() where id = 1"是否与"select id from resources where id = 5"相同?(假设资源表id列上有索引)。
CREATE OR REPLACE FUNCTION permitted_resources()
  RETURNS TABLE (id   int, name varchar(10)) AS
$func$
BEGIN
   RETURN QUERY
   SELECT r.id, r.name from resources r; 
END
$func$  LANGUAGE plpgsql;发布于 2020-08-27 13:25:12
将“从permitted_resources()选择id ()其中id = 1”与“从资源选择id = 5”相同吗?
不,不会的。PL/pgSQL函数是优化器的黑匣子。
如果您想实现这样的目标,请使用language sql函数:
CREATE OR REPLACE FUNCTION permitted_resources()
  RETURNS TABLE (id   int, name varchar(10)) AS
$func$
   SELECT r.id, r.name from resources r; 
$func$  
LANGUAGE sql
stable;我们可以使用以下设置进行测试:
create table test 
(
  id integer primary key, 
  some_nr integer default random() * 1000 + 1,
  some_date date default current_date,
  some_text text default md5(random()::text)
);
insert into test (id) 
select *
from generate_series(1,1e6);现在创建一个PL/pgSQL函数:
create function get_data1()
returns setof test
as
$$
begin
 return query
   select *
   from test;
end;   
$$
language plpgsql
stable;和一个SQL函数:
create function get_data2()
returns setof test
as
$$
 select *
 from test;
$$
language sql
stable;让我们看看执行计划的外观:
explain (analyze)
select *
from get_data1() -- this is the PL/pgSQL function
where id = 1234; 产生以下执行计划:
Function Scan on get_data1  (cost=0.25..4.75 rows=5 width=44) (actual time=261.033..361.218 rows=1 loops=1)
  Filter: (id = 1234)
  Rows Removed by Filter: 999999
Planning Time: 0.033 ms
Execution Time: 371.302 ms显然,它首先检索所有行,然后再丢弃它们。
然而,
explain (analyze)
select *
from get_data2() -- the "SQL" function
where id = 1234; 产生以下执行计划:
Index Scan using test_pkey on test  (cost=0.42..2.43 rows=1 width=45) (actual time=0.015..0.017 rows=1 loops=1)
  Index Cond: (id = 1234)
Planning Time: 0.119 ms
Execution Time: 0.031 ms这个功能在计划中甚至不再被提及。毫不奇怪,一个简单的选择会产生同样的计划:
explain (analyze)
select *
from test
where id = 1234;Index Scan using test_pkey on test  (cost=0.42..2.43 rows=1 width=45) (actual time=0.014..0.014 rows=1 loops=1)
  Index Cond: (id = 1234)
Planning Time: 0.058 ms
Execution Time: 0.026 ms我不知道这是否适用于更复杂的查询,但是这样一个函数与另一个表之间的简单连接显示了相同的行为。
https://stackoverflow.com/questions/63616639
复制相似问题