postgres查询current_date上的分区表

时间:2017-11-17 22:27:02

标签: postgresql postgresql-9.4 database-partitioning

我在postgres中有一个包含10百万行的表,并且每月按日期列'created_on'进行分区。我的问题是我经常需要从现在开始以一段时间间隔查询这样的表。

但是,如果尝试

SELECT * 
FROM partitioned_table pt 
WHERE pt.created_on>current_date - '10 days'::INTERVAL

这会覆盖所有分区表。

如果我使用固定日期字符串执行相同的查询:

SELECT * 
FROM partitioned_table pt
WHERE pt.created_on>'2017-11-17 - '10 days'::INTERVAL

这仅限于最后一个分区表。

显然会发生这种情况,因为current_date是动态分配的。知道如何处理它而不需要每次都指定日期吗?

1 个答案:

答案 0 :(得分:0)

我对分区查询有同样的问题。
解决方案之一是使用查询参数。
例如:

do $$
    declare x json;
    dt date;
    begin
        dt = current_date;
        explain(format json) into x select * from sr_scgenerated where date > dt;
        raise notice '%', x;
    end;
$$
  

约束排除仅在查询的WHERE子句包含   常量(或外部提供的参数)。例如,一个   与不可更改的函数(例如CURRENT_TIMESTAMP)进行比较   无法优化,因为计划者无法知道哪个分区   函数值可能会在运行时出现。

https://www.postgresql.org/docs/11/ddl-partitioning.html

prepare query(date) as 
    select * from sr_scgenerated where date > $1;
   explain analyze execute query(current_date);
deallocate query;

来自http://www.peterhenell.se/msg/PostgreSQL---Partition-Exclusion-with-nowcurrent_timestampcurrent_date