这些不好的数据是在什么时候影响我们的呢? 下面来看一个例子。
- EXPLAIN ANALYZE SELECT col1,col2,count(*) from tbl group by col1, col2;
- QUERY PLAN
- -----------------------------------------------------------------------------------------------------------------------------
- GroupAggregate (cost=1990523.20..2091523.04 rows=100000 width=16) (actual time=2697.246..4470.789 rows=1001 loops=1)
- Group Key: col1, col2
- -> Sort (cost=1990523.20..2015523.16 rows=9999984 width=8) (actual time=2695.498..3440.880 rows=10000000 loops=1)
- Sort Key: col1, col2
- Sort Method: external sort Disk: 176128kB
- -> Seq Scan on tbl (cost=0.00..144247.84 rows=9999984 width=8) (actual time=0.008..665.689 rows=10000000 loops=1)
- Planning time: 0.072 ms
- Execution time: 4494.583 ms
聚合行时,Postgres 选择做散列聚合或组合。 如果它认为散列表合适,则选择散列聚合,否则它会选择对所有行进行排序,然后按照 col1、col2 对它们进行分组。
现在,planner 估计组的数量(等于 col1、col2 的不同值的数量)将为 100000。它预计到它没有足够的 work_mem 将该散列表存储在内存中。 因此,它使用基于磁盘的排序来运行该查询。 但是,正如在查询计划中所看到的那样,实际行数仅为 1001。也许,我们有足够的内存来执行哈希聚合。
让 planner 去捕获 n_distinct 统计信息,重新运行查询并找出结果。
- CREATE STATISTICS s2 (ndistinct) on col1, col2 from tbl;
- ANALYZE tbl;
-
- EXPLAIN ANALYZE SELECT col1,col2,count(*) from tbl group by col1, col2;
- QUERY PLAN
- -----------------------------------------------------------------------------------------------------------------------
- HashAggregate (cost=219247.63..219257.63 rows=1000 width=16) (actual time=2431.767..2431.928 rows=1001 loops=1)
- Group Key: col1, col2
- -> Seq Scan on tbl (cost=0.00..144247.79 rows=9999979 width=8) (actual time=0.008..643.488 rows=10000000 loops=1)
- Planning time: 0.129 ms
- Execution time: 2432.010 ms
- (5 rows)
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|