我在 Postgres 8.3.5 中有一个函数,它从多个表中选择数据并将结果转储到一个表中:
create or replace function test_function_2(startdate timestamp, enddate timestamp)
returns void as $$
begin
delete from cl_final_report;
INSERT INTO cl_final_report
SELECT
b.batchkey AS batchnumber,
pv.productkey,
p.name AS productname,
avg(r.value) AS avgchemlean,
sum(r.auxvalue) AS totalweight,
max(o.time) AS timecompleted
FROM result r
LEFT JOIN physicalvalue pv ON r.physicalvaluekey = pv.physicalvaluekey
LEFT JOIN product p ON pv.productkey = p.productkey
LEFT JOIN object o ON r.objectkey = o.objectkey
LEFT JOIN batch b ON o.batchkey = b.batchkey
WHERE pv.name = 'CL'::text AND
and o.time between startdate and enddate
GROUP BY b.batchkey, pv.productkey, p.name
end
$$ language plpgsql;
使用 PgAdmin 并执行此命令需要 113 秒才能完成此功能:
select test_function_2('05/02/2013', '05/03/2013')
但是,如果我用这样的文字替换函数中的输入变量:
create or replace function test_function_2(startdate timestamp, enddate timestamp)
returns void as $$
begin
delete from cl_final_report;
INSERT INTO cl_final_report
SELECT
b.batchkey AS batchnumber,
pv.productkey,
p.name AS productname,
avg(r.value) AS avgchemlean,
sum(r.auxvalue) AS totalweight,
max(o.time) AS timecompleted
FROM result r
LEFT JOIN physicalvalue pv ON r.physicalvaluekey = pv.physicalvaluekey
LEFT JOIN product p ON pv.productkey = p.productkey
LEFT JOIN object o ON r.objectkey = o.objectkey
LEFT JOIN batch b ON o.batchkey = b.batchkey
WHERE pv.name = 'CL'::text AND
and o.time between '05/02/2013' and '05/03/2013'
GROUP BY b.batchkey, pv.productkey, p.name
end
$$ language plpgsql;
该函数在不到 5 秒内执行。
我是 Postgres 的新手,所以我可能缺少一些东西,但我似乎无法在任何地方找到答案。