【发布时间】:2009-09-29 23:01:31
【问题描述】:
我有相当长且复杂的 SQL 查询,它是针对 PostgreSQL 8.3 运行的。部分查询涉及过滤以今天结尾的日期范围,如下所示:
where ...
and sp1.price_date between current_date::date - '1 year'::interval and current_date::date
and sp4.price_date between current_date::date - '2 weeks'::interval and current_date::date
and sp5.price_date = (select sp6.price_date
from stock_prices sp6
where sp6.stock_id = s.stock_id
and sp6.price_date < current_date::date
order by sp6.price_date desc
limit 1)
...
此查询运行(第一次)大约需要 5 分钟,第二次运行大约需要 1.5 分钟。从 EXPLAIN ANALYZE 输出看来,current_date 似乎是问题所在。所以我尝试用硬编码的日期替换它,如下所示:
where ...
and sp1.price_date between '2009-09-30'::date - '1 year'::interval and '2009-09-30'::date
and sp4.price_date between '2009-09-30'::date - '2 weeks'::interval and '2009-09-30'::date
and sp5.price_date = (select sp6.price_date
from stock_prices sp6
where sp6.stock_id = s.stock_id
and sp6.price_date < '2009-09-30'::date
order by sp6.price_date desc
limit 1)
...
查询然后在半秒内运行!这很好,除了日期在查询中总共出现 10 个位置,当然,我不希望用户必须在 10 个位置手动更改它。在 MS SQL Server 中,我会简单地用当前日期的值声明一个变量并使用它,但是 apparently 在 Postgres 的普通 SQL 中是不可能的。
如何在自动使用当前日期的同时使该查询快速运行?
【问题讨论】:
-
current_date::date 这很奇怪,如果 ::date 已经是 date 类型,为什么还需要它呢?此外,如果您从日期中添加/减去间隔,则结果无论如何都会是时间戳!
标签: sql postgresql