首页 > 解决方案 > 加速查询日期变量

问题描述

我需要使用脚本查询昨天每天早上生成的数据。

查询就像

select xxx 
from table 
where create_time >= current_date - 1 
  and create_time < current_date 
limit 10;

它的查询计划是:

                   QUERY PLAN                                     
------------------------------------------------------------------------------------
 Limit  (cost=100.00..117.64 rows=3 width=138)
   ->  Foreign Scan on table  (cost=100.00..117.64 rows=3 width=138)

上面的查询需要很长时间。

但是,当我使用如下所示的固定时间时,它会立即返回结果......

select xxx 
from table 
where create_time >= '2020-07-30 00:00:00' 
  and create_time < '2020-08-03 00:00:00' 
limit 10;

其查询计划为:10;

                                       QUERY PLAN                                       
----------------------------------------------------------------------------------------
 Limit  (cost=100.00..131.46 rows=3 width=138)
   ->  Foreign Scan on table (cost=100.00..131.46 rows=3 width=138)
         Filter: ((create_time < CURRENT_DATE) AND (create_time >= (CURRENT_DATE - 1)))

是什么造成了这种差异?以及如何加速第一次查询?

标签: postgresql

解决方案


显然table是一张外国桌子。Postgres 外部数据包装器无法将表达式下推到外部服务器,因为服务器可能对运行查询的current_date - 1服务器有不同的想法。current_date所以它必须从远程服务器获取所有行并在运行查询的服务器上进行过滤。

可以将常量值下推到外部服务器,以便仅返回符合条件的行(并发送网络)(很可能使用索引)。


推荐阅读