【问题标题】:Postgres inner query performancePostgres 内部查询性能
【发布时间】:2016-11-18 16:06:04
【问题描述】:

我有一张表,我需要使用此规则从所有内容中进行选择:

id = 4524522000143 and validPoint = true
and date >  (max(date)- interval '12 month')
-- the max date, is the max date for this id

解释规则:我必须获取所有寄存器并计算它们,它们必须至少 1 年从最新的寄存器开始。

这是我的实际查询:

WITH points as (
    select 1 as ct from base_faturamento_mensal
    where id = 4524522000143 and validPoint = true
    group by id,date
    having date >  (max(date)- interval '12 month')
)  select sum(ct) from points

有没有更有效的方法?

【问题讨论】:

    标签: sql performance postgresql group-by


    【解决方案1】:

    您的查询使用了在HAVING 子句中包含一个未聚合列的技巧,但我认为这并不是特别糟糕。看起来不错,但如果没有EXPLAIN ANALYZE <query> 输出,我就不能说更多了。

    要做的一件事是,您可以摆脱 CTE 并在同一查询中使用 count(*),而不是返回 1,然后在其上运行 sum

    select count(*) as ct
    from base_faturamento_mensal
    where id = 4524522000143 
      and validPoint = true
    group by id, date
    having date > max(date) - interval '12 months'
    

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 1970-01-01
      • 2023-03-30
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2013-05-02
      • 2015-08-15
      • 2020-06-02
      相关资源
      最近更新 更多