【问题标题】:variable date filter on large table too slow大表上的可变日期过滤器太慢
【发布时间】:2019-06-14 10:20:38
【问题描述】:

我有一个包含 2500 万条记录的巨大表,以及一个具有可以执行查询的计划任务的系统。查询需要通过创建日期(时间戳)列快速获取最新记录并应用一些计算。这样做的问题是日期也保存在表中,并且每次执行都会更新为最新的执行日期。它确实有效,但速度很慢:

select * from request_history
where createdate > (select startdate from request_history_config)
limit 10;

大约需要 20 秒才能完成,与此相比,这慢得令人难以置信:

set custom.startDate = '2019-06-13T18:02:04';
select * from request_history
where createdate > current_setting('custom.startDate')::timestamp
limit 10;

这个查询在 100 毫秒内完成。问题是我无法更新和保存下一次执行的日期!我正在寻找 SET 变量 TO 语句,它可以让我从表中获取一些值,但所有这些尝试都不起作用:

select set_config('custom.startDate', startDate, false) from request_history_config;
// ERROR:  function set_config(unknown, timestamp without time zone, boolean) does not exist

set custom.startDate to (select startDate from request_history_config);
// ERROR:  syntax error at or near "("

【问题讨论】:

  • 如何将其拆分为两个语句:一个查询request_history_config,另一个使用第一个语句的结果?
  • 查询实际上需要很长时间才能执行,还是您正在等待 request_history_config 上的锁释放?

标签: postgresql postgresql-9.5


【解决方案1】:

你可以使用这样的函数来做到这一点:

CREATE OR REPLACE FUNCTION get_request_history()
 RETURNS TABLE(createdate timestamp)
 LANGUAGE plpgsql
AS $function$
DECLARE
  start_date timestamp;
BEGIN
   SELECT startdate INTO start_date FROM request_history_config;
   RETURN QUERY
   SELECT *
   FROM   request_history h
   WHERE  h.createdate > start_date
   LIMIT 10;
END
$function$

然后使用函数获取值:

select * from get_request_history()

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    • 2012-04-04
    相关资源
    最近更新 更多