【问题标题】:postgres query partitioned table on current_datepostgres 在 current_date 查询分区表
【发布时间】:2017-11-17 22:27:02
【问题描述】:

我在 postgres 中有一个包含 1000 万行的表,它每月按日期列“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 是动态分配的。知道如何处理它而无需每次都指定日期吗?

【问题讨论】:

    标签: postgresql postgresql-9.4 database-partitioning


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多