微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我想有一个返回表的函数。我知道用户可以像表一样使用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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?