在PostgreSQL中,在同一个查询中多次调用同一个函数的最佳方法是什么?
示例:
SELECT a.id,
sum_one(a.id) AS "Sum_one",
sum_two(a.id) AS "Sum_two",
(sum_one(a.id )+sum_two(a.id)) AS "Sum_three"
FROM a
sum_one()
和sum_two()
是函数。我重复sum_one()
和sum_two()
的来电。这将减慢大型数据库中的查询速度。
我想避免以下声明。
(sum_one(a.id )+sum_two(a.id)) AS "Sum_three"
我怎么能在PostgreSQL中做到这一点?
答案 0 :(得分:2)
您应将功能波动率设置为Stable
。
More about function volatility
CREATE OR REPLACE FUNCTION myFunc(prm_MyParam integer)
RETURNS numeric AS
$BODY$
BEGIN
{...}
END;$BODY$
LANGUAGE plpgsql STABLE;
答案 1 :(得分:0)
使用子查询:
SELECT
"Sum_one",
"Sum_two",
("Sum_one" + "Sum_two") AS "Sum_three"
FROM (
SELECT sum_one("A"."id") AS "Sum_one", sum_two("A"."id") AS "Sum_two" FROM A
)