PostgreSQL:如何在PostgreSQL中减少查询执行时间?

PostgreSQL:如何在PostgreSQL中减少查询执行时间?,postgresql,Postgresql,我有一个包含数百万条记录的表,但是当我想要检索一些行时,处理查询会花费更多的时间 例如: --桌子 --插入记录的函数 CREATE OR REPLACE FUNCTION insertemployee() RETURNS void AS $BODY$ declare i int :=0; begin while(i<100000) loop insert into employee values(i,now());

我有一个包含数百万条记录的表,但是当我想要检索一些行时,处理查询会花费更多的时间

例如:
--桌子

--插入记录的函数

CREATE OR REPLACE FUNCTION insertemployee()  
RETURNS void AS  
$BODY$  
declare  
i int :=0;  
begin  
    while(i<100000)   
    loop   
    insert into employee values(i,now());  
    i:=i+1;  
    end loop;  
end;  
$BODY$  
LANGUAGE plpgsql;  
--函数来检索行

CREATE OR REPLACE FUNCTION retrieveemployee() RETURNS TABLE (empid int,empdate timestamp) AS  
$body$  
begin    
       return query    
       select e.empid,e.empdate from employee AS e WHERE e.empid BETWEEN 1000 and   80000;    
end;    
$body$    
LANGUAGE plpgsql;    
--函数执行

select * from retrieveemployee();

Total query runtime: 1382 ms.

现在还不完全清楚您的问题是什么,但通常一个好主意是在您的表上有一个主键,在您定期搜索的任何其他列上有索引(主键也是一个索引,其限制是它是唯一的)


相反,与其使用带有定义的
RETURNS TABLE
,不如使用函数
RETURNS SETOF employee
,使事情更易于理解和维护。

您的
insertemployee()
函数可以替换为一个insert语句:
insert into employee(empid,empdate)select i,now()从generate_series(1100000)i
@a_horse_,没有名字,非常感谢。
CREATE OR REPLACE FUNCTION retrieveemployee() RETURNS TABLE (empid int,empdate timestamp) AS  
$body$  
begin    
       return query    
       select e.empid,e.empdate from employee AS e WHERE e.empid BETWEEN 1000 and   80000;    
end;    
$body$    
LANGUAGE plpgsql;    
select * from retrieveemployee();

Total query runtime: 1382 ms.