直接查询表与返回同一表的查询函数之间的区别

问题描述

我想有一个返回表的函数。我知道用户可以像表一样使用select和join中的函数调用。但是,select / join是否能够使用TABLE函数返回的源表的索引?

例如: "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;

解决方法

“从id = 1的allowed_resources()中选择id”是否与“从id = 5的资源中选择id”相同?

不,不会。 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

我不知道这对于更复杂的查询是否成立,但是在此函数与另一个表之间的简单连接会显示相同的行为。