2017-08-17 15 views
1

このクエリは、ウィンドウが大きすぎるためすぐに完了しません。それをスピードアップする方法はありますか?アクティブユーザークエリを高速化

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; 
+0

'messages(direction、created_at)'列で複数列のインデックスを試してみてください。 – krokodilko

答えて

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を使用して効率的なプランを自由に選択できます。

+0

素晴らしいですが、これがなぜより速いのか分かりませんか? (それは...ですが) –

+0

'explain select ... 'でそれぞれを実行すると、クエリプランが表示されます。その理由を彼らと区別することが可能でなければならない – gcbenison