0

我有一个慢查询,我想优化它。该查询与以下示例非常相似:

DROP TABLE IF EXISTS test;
CREATE TABLE test (i integer);

DROP TABLE IF EXISTS test2;
CREATE TABLE test2 (i integer);
INSERT INTO test2 VALUES (1);
INSERT INTO test2 VALUES (2);
INSERT INTO test2 VALUES (3);
INSERT INTO test2 VALUES (4);
INSERT INTO test2 VALUES (5);
INSERT INTO test2 VALUES (6);

DROP TABLE IF EXISTS test3;
CREATE TABLE test3 (i integer, c1 varchar(100), c2 varchar(100));
INSERT INTO test3 VALUES (4, 'hello', 'world');
INSERT INTO test3 VALUES (7, 'hello', 'world');
INSERT INTO test3 VALUES (2, 'world', 'hello');
INSERT INTO test3 VALUES (120, 'world', 'hello');

EXPLAIN ANALYZE INSERT INTO test 
SELECT *
FROM test2
WHERE test2.i NOT IN 
    (SELECT min(i) FROM test3 GROUP BY c1, c2 HAVING COUNT(*) > 1);

分析打印以下内容:

                                                       QUERY PLAN                                                       
------------------------------------------------------------------------------------------------------------------------
 Insert on test  (cost=15.95..55.95 rows=1200 width=4) (actual time=0.098..0.098 rows=0 loops=1)
   ->  Seq Scan on test2  (cost=15.95..55.95 rows=1200 width=4) (actual time=0.037..0.039 rows=4 loops=1)
         Filter: (NOT (hashed SubPlan 1))
         SubPlan 1
           ->  HashAggregate  (cost=13.40..15.52 rows=170 width=440) (actual time=0.017..0.018 rows=2 loops=1)
                 Filter: (count(*) > 1)
                 ->  Seq Scan on test3  (cost=0.00..11.70 rows=170 width=440) (actual time=0.001..0.001 rows=4 loops=1)
 Total runtime: 0.200 ms
(8 rows)

(真正的查询处理更多的数据。)

是否loops=1意味着 PostgreSQL 缓存了子查询的结果?请注意,子查询适用于 table test3,因此它独立于查询的其他部分。(有没有其他方法可以确定 PostgreSQL 是否缓存了这个子查询?)

4

1 回答 1

1

不,PostgreSQL 不使用子查询进行缓存。它能够物化一些数据,但你可以在计划中看到它。只有一个子查询调用请求。

于 2013-10-30T12:13:52.077 回答