我使用Postgresql,它用于报告.目前配置的方式如下:
有一个复杂的查询返回报告数据,如下所示:
select Column1 as Name1,Column2 as Name2 from soMetable tbl inner join ... where ... and ... and $1 <= somedate and $2 >= somedate group by ... order by ...;
CREATE OR REPLACE FUNCTION GetMyReport(IN fromdate timestamp without time zone,IN todate timestamp without time zone) RETURNS TABLE(Name1 character varying,Name2 character varying) AS $BODY$ --query start select Column1 as Name1,Column2 as Name2 from soMetable tbl inner join ... where ... and ... and $1 <= somedate and $2 >= somedate group by ... order by ...; --query end $BODY$ LANGUAGE sql VOLATILE COST 10 ROWS 1000;
select null::text as Name1,Name2 from GetMyReport ('2012-05-28T12:19:39.0000000+11:00'::timestamp,'2012-05-28T12:19:44.0000000+11:00'::timestamp);
我的问题是:
>当我对数据库运行“查询”时,它运行得非常快.事实上,如果返回的数据相当小,只需几秒钟
>当我运行从报告应用程序传递的sql时,每次运行都需要花费精力.事实上,查询返回的相同数据在几秒钟内超过10分钟.
>实际上,我可以运行原始查询,需要几毫秒,运行函数 – 需要大约10分钟,再次运行查询 – 毫秒,运行函数 – 再次10分钟,所有参数完全相同.
可能是什么原因?
好的,这很容易.事实证明数据库必须在知道参数之前准备查询计划,这会导致不良结果.解决方案是使用plpgsql并返回QUERY EXECUTE.现在性能与预期一致.
原文链接:https://www.f2er.com/postgresql/192456.htmlCREATE OR REPLACE FUNCTION GetMyReport(IN fromdate timestamp without time zone,Name2 character varying) AS $BODY$ BEGIN RETURN QUERY EXECUTE' select Column1 as Name1,Column2 as Name2 from soMetable tbl inner join ... where ... and ... and $1 <= somedate and $2 >= somedate group by ... order by ...;' USING $1,$2 END $BODY$ LANGUAGE plpgsql VOLATILE COST 10 ROWS 1000;