加快活动用户查询

时间:2017-08-17 21:34:33

标签: sql postgresql

此查询现在尚未完成,因为窗口太大。有什么方法可以加快速度吗?

select
    gs.date,
    (select count(distinct customer_id) 
     from messages 
     where direction = 'received' 
       and created_at between gs.date - interval '89 days' and gs.date)
from
    generate_series('2015-07-09'::date, current_date::date, interval '1 day') gs
order by gs.date;

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

select
  gs.date,
  count(distinct(customer_id))
from
  messages
  inner join generate_series('2015-07-09'::date, current_date::date, interval '1 day') gs
where
  direction = 'received'
  and created_at between gs.date - interval '89 days' and gs.date
group by gs.date
order by gs.date

它仍然是一个昂贵的查询(执行滚动唯一计数,这只是一个固有的昂贵的计算)但我认为这将比在您的select子句中有一个子查询更快。查询计划员可以更自由地使用联接和group by选择有效的计划。