@klin的回覆是正確的,我有一個建議。改用SQL語言。在描述的情況下,PostgreSQL規劃人員可以使用更好的計劃。 PLPGSQL功能是黑箱的策劃人:
CREATE OR REPLACE FUNCTION public.foo1()
RETURNS integer[]
LANGUAGE plpgsql
AS $function$
BEGIN
RETURN ARRAY[1,2,3,4];
END;
$function$
CREATE OR REPLACE FUNCTION public.foo2()
RETURNS integer[]
LANGUAGE sql
AS $function$
SELECT ARRAY[1,2,3,4];
$function$
CREATE TABLE boo(a int);
INSERT INTO boo SELECT random()*10 FROM generate_series(1,10000);
ANALYZE boo;
postgres=# EXPLAIN ANALYZE SELECT * FROM boo WHERE a = ANY(foo1());
QUERY PLAN
═════════════════════════════════════════════════════════════════════════════════════════════════════
Seq Scan on boo (cost=0.00..2770.00 rows=6145 width=4) (actual time=0.118..49.949 rows=4104 loops=1)
Filter: (a = ANY (foo1()))
Rows Removed by Filter: 5896
Planning time: 0.096 ms
Execution time: 50.900 ms
(5 rows)
Time: 51.771 ms
postgres=# EXPLAIN ANALYZE SELECT * FROM boo WHERE a = ANY(foo2());
QUERY PLAN
═══════════════════════════════════════════════════════════════════════════════════════════════════
Seq Scan on boo (cost=0.00..195.00 rows=4104 width=4) (actual time=0.036..4.700 rows=4104 loops=1)
Filter: (a = ANY ('{1,2,3,4}'::integer[]))
Rows Removed by Filter: 5896
Planning time: 0.193 ms
Execution time: 5.254 ms
(5 rows)
隨着SQL函數是稍微好一點的結果估計。 SQL函數是一個宏 - 如果你使用SQL函數,那麼就相當於直接寫查詢:
postgres=# EXPLAIN ANALYZE SELECT * FROM boo WHERE a = ANY(ARRAY[1,2,3,4]);
QUERY PLAN
═══════════════════════════════════════════════════════════════════════════════════════════════════
Seq Scan on boo (cost=0.00..195.00 rows=4104 width=4) (actual time=0.032..4.782 rows=4104 loops=1)
Filter: (a = ANY ('{1,2,3,4}'::integer[]))
Rows Removed by Filter: 5896
Planning time: 0.122 ms
Execution time: 5.325 ms
(5 rows)
在這種情況下,optimalizer有更多的信息,可以使用它。對於結果不變的函數,SQL函數通常更好。
謝謝!這正是我需要的。 – DJTripleThreat
我更喜歡數組[1,2,3,4]在字符串表示法上 –