DBAtlas · 数据库运维图谱

为相关列创建扩展统计信息(CREATE STATISTICS)

PostgreSQL维护

命令

-- city and district are correlated: the planner assumes independence and underestimates rows
CREATE STATISTICS customer_city_district_stx (dependencies, ndistinct, mcv) ON city, district FROM customer;
ANALYZE customer;

-- Collected statistics
SELECT statistics_name, attnames, kinds, n_distinct, dependencies
FROM pg_stats_ext
WHERE tablename = 'customer';

-- Verify: estimated rows should now be close to actual rows
EXPLAIN (ANALYZE, TIMING OFF)
SELECT * FROM customer WHERE city = 'Ankara' AND district = 'Cankaya';

作用

让规划器了解列之间的相关性(函数依赖、组合 distinct 计数、联合最常见值);修正多列 WHERE 和 GROUP BY 条件的行数估算。

适用场景

当 EXPLAIN ANALYZE 显示多列过滤的估算行数远低于实际(例如 12 对 570),并因此选择了错误的连接方法/索引时。

注意

只有在 ANALYZE 之后才生效。当列组合数量远高于统计信息目标(默认 100)时,mcv 列表无法覆盖其中的大部分,此时 mcv 可能无法修正 dependencies 能够修正的估算。请用 EXPLAIN 验证;必要时从定义中去掉 mcv,或用 ALTER STATISTICS customer_city_district_stx SET STATISTICS 1000; 调高目标。dependencies 只用于等值/IN 条件,ndistinct 用于 GROUP BY 估算。每个定义都会延长 ANALYZE;只为已证实存在估算错误的列组添加。

在 DBAtlas 中打开 →

相关内容