繁体   English   中英

PostgreSQL generate_series 奇怪的行为

[英]PostgreSQL generate_series strange behaviour

以下两个查询产生完全相同的输出:

select
  ref_date::date
from generate_series('2020-10-01', '2020-10-01'::date, interval '1 day') ref_date
--   ref_date
-- 2020-10-01

select now()::date ref_date
--   ref_date
-- 2020-10-01

但是,在对它们中的每一个运行explain时,我们会得到不同的结果:

# query 1
Function Scan on generate_series ref_date  (cost=0.01..12.51 rows=1000 width=4)

# query 2
Result  (cost=0.00..0.01 rows=1 width=4)

当在一系列连接中包含一个或另一个时,情况会变得更糟,连接条件基于ref_date

select
  stuff
from (select ref_date::date from generate_series('2020-10-01', '2020-10-01'::date, interval '1 day') ref_date) ref_date
left join (other_stuff) x on true
left join (more_stuff) y on y.id = x.id and y.timestamp < ref_date
-- executes in 10 minutes
-- EXPLAIN is long and complex
-- query uses index on more_stuff.(id) only
   despite an index on (id, timestamp) being available

select
  stuff
from (select now()::date ref_date) ref_date
left join (other_stuff) x on true
left join (more_stuff) y on y.id = x.id and y.timestamp < ref_date
-- executes in ten milliseconds
-- EXPLAIN is short and simple
-- query adequately uses index on more_stuff.(id, timestamp)

我不能在现实中使用now()::date的原因是我需要generate_series()来生成多个日期(例如,跨越 5 年)。

问题

有没有一种方法可以使用使用日期序列的替代方法,并且与在上述示例中使用now()::date时一样有效?

笔记:

  • 即使只生成一个日期generate_series()方法的性能也比now()::date差很多
  • 使用带有 generate_series 输出的预构造表(而不是直接在查询中使用 generate_series)产生与直接使用函数相同的结果,即使在该表上有索引
  • 可以在此处找到两个版本(now() 和 generate_series())的 EXPLAIN ANALYZE 输出: https : //gist.github.com/JivanRoquet/a4f1c82ecf54b420844e652584317c76

相关子查询可以满足您的要求。

select stuff
FROM generate_series('2020-09-01'::date, '2020-10-01'::date, interval '1 day') as ref_date
LEFT JOIN LATERAL
(select (other_stuff)) AS x on true
left join (more_stuff) y on y.timestamp < ref_date

这应该生成一个嵌套循环连接,内部部分的计划与您的快速查询相匹配。 LATERAL 关键字强制数据库为左侧的每一行重新评估右侧。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM