複数のテーブルからデータを選択し、結果を単一のテーブルにダンプする 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を初めて使用するので、おそらく何かが欠けている可能性がありますが、どこにも答えが見つからないようです.