Postgres虽然循环真的很慢

时间:2014-09-09 19:47:38

标签: sql postgresql plpgsql

我得到了这个sproc,我得到的音量取决于“FlowVolume”它可能是1,10,100。我发现这个工作的唯一方法是当前的实现,但是真的很慢。另一种方法是在“时间戳”中设置间隔,可以是每12秒,每2分钟或每20分钟间隔。

CREATE OR REPLACE FUNCTION "getBLTPoints"(IN id integer)
RETURNS TABLE(times text, bio text, particles text) AS

$BODY$
DECLARE
currVol real;
currbio integer;
currpart integer;
times timestamp with time zone;
totalvol integer;
profileid integer;
analysisopt integer;
analysisvol integer;
counter integer;
BEGIN
--Getting the right profile to get the line,autosample,analysis volume
select "ProfileID"into profileid from "Samples" where "ID" = id;
--Getting the mode that the system was in when sample was done
select "optBaseVolume" into analysisopt from "Profiles" where "ID" = profileid;
if(analysisopt = 0) then
    analysisvol = 1;
elseif(analysisopt = 1) then
    analysisvol = 10;
else
    analysisvol = 100;
end if;
counter = analysisvol;
--Getting the totalvolume to run it in the while loop until it reaches the totalvolume
select floor("FlowVolume")::integer into totalvol from "Results" where "SampleID" = id order by "FlowVolume" desc limit 1;

WHILE counter <= totalvol LOOP
    RETURN QUERY
    select extract('epoch' from "Timestamp")::text,"BioAccumulated"::text, "TotalParticlesAccum"::text from 
    "Results" where "SampleID" = id and "FlowVolume" = counter; 

    counter = counter + analysisvol;

END LOOP;
END;

1 个答案:

答案 0 :(得分:2)

在任何循环内使用RETURN QUERY都不能快。由于嵌套查询速度很快,因此循环速度很快。但你可以使用明显更快的技术..你可以通过函数generate_series生成一个计数器系列,你可以将这个系列加入你的“结果”表:

RETURN QUERY SELECT extract('epoch' FROM "Timestamp")::text,
                    "BioAccumulated"::text,
                    "TotalParticlesAccum"::text
                FROM "Result"
                     JOIN generate_series(analysisvol, totalvol, analysisvol) g(v)
                     ON "Result"."FlowVolume" = g.v
               WHERE "SampleID" = id;