我刚刚重组了我的数据库以使用 partitioning在 Postgres 8.2 中。现在我遇到了查询性能问题:
SELECT *
FROM my_table
WHERE time_stamp >= '2010-02-10' and time_stamp < '2010-02-11'
ORDER BY id DESC
LIMIT 100;
表中有 4500 万行。在分区之前,这将使用反向索引扫描并在达到限制时立即停止。
分区后(在 time_stamp 范围内),Postgres 对主表和相关分区进行全索引扫描并合并结果,对它们进行排序,然后应用限制。这花费的时间太长了。
我可以用:
SELECT * FROM (
SELECT *
FROM my_table_part_a
WHERE time_stamp >= '2010-02-10' and time_stamp < '2010-02-11'
ORDER BY id DESC
LIMIT 100) t
UNION ALL
SELECT * FROM (
SELECT *
FROM my_table_part_b
WHERE time_stamp >= '2010-02-10' and time_stamp < '2010-02-11'
ORDER BY id DESC
LIMIT 100) t
UNION ALL
... and so on ...
ORDER BY id DESC
LIMIT 100
这运行得很快。时间戳超出范围的分区甚至不包含在查询计划中。
我的问题是:在 Postgres 8.2 中是否可以使用一些提示或语法来防止查询计划程序扫描整个表但仍然使用仅引用主表的简单语法?
基本上,我是否可以避免在当前定义的每个分区上动态构建大型 UNION 查询的痛苦?
编辑:我启用了 constraint_exclusion(感谢@Vinko Vrsalovic)
最佳答案
您是否尝试过约束排除(您链接到的文档中的第 5.9.4 节)
Constraint exclusion is a query optimization technique that improves performance for partitioned tables defined in the fashion described above. As an example:
SET constraint_exclusion = on;
SELECT count(*) FROM measurement WHERE logdate >= DATE '2006-01-01';
Without constraint exclusion, the above query would scan each of the partitions of the measurement table. With constraint exclusion enabled, the planner will examine the constraints of each partition and try to prove that the partition need not be scanned because it could not contain any rows meeting the query's WHERE clause. When the planner can prove this, it excludes the partition from the query plan.
You can use the EXPLAIN command to show the difference between a plan with constraint_exclusion on and a plan with it off.
关于sql - 多分区Postgres表的高效查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2236776/