2016-10-25 56 views
-1

我寫一個SQL查詢在特定日期Nestesed SQL查詢到以太多的時間來執行

查詢來計算用戶的總數量低於: -

select plan_date, type_name, account_type_id, new_type 
FROM (
    select 
     final_reporting_db.plan_change_facts.date as plan_date, 
     final_reporting_db.plan_dim.account_type as type_name, 
     final_reporting_db.plan_dim.id as account_type_id, 
     (
      select count(*) as new_type from final_reporting_db.plan_change_facts 
      where final_reporting_db.plan_change_facts.plan_status_dim_id = account_type_id 
      and final_reporting_db.plan_change_facts.date = plan_date 
     ) as new_type 
    FROM 
     final_reporting_db.plan_change_facts 
    INNER JOIN final_reporting_db.plan_dim where final_reporting_db.plan_dim.id in(1,2,3,4,5,6,8,9,13) 
) main_table where plan_date between '2016-04-24' and '2016-04-28' group by plan_date, type_name; 

在此查詢子查詢需要花費太多時間來執行,因爲它正在計算該日期的計數。

我很困惑如何提高此查詢性能。 ,因爲它需要36秒才能執行。 是否有任何方式使用group by子句而不是使用嵌套查詢。 幫助將不勝感激

+4

請用您正在使用的數據庫標記您的問題。 –

+2

並添加查詢的執行計劃。如果是Postgres,那麼'explain(analyze,verbose)'的輸出。對於其他DBMS儘可能詳細。 [*格式化*](http://stackoverflow.com/editing-help#code)**文本**,請[無屏幕截圖](http://meta.stackoverflow.com/questions/285551/why-may -i-不上傳圖像-的代碼上那麼當灰化-A-問題/ 285557#285557) –

回答

1

這是太長的評論。

首先,您的查詢幾乎是不可讀的。我已經想出的最好的是:

select cf.date as plan_date, 
     d.account_type as type_name, d.id as account_type_id, 
     (select count(*) as new_type 
     from final_reporting_db.plan_change_facts cf2 
     where cf2.plan_status_dim_id = ??.account_type_id and 
       cf2.date = ??.plan_date 
-------------------------^ I assume this should be cf 
     ) as new_type 
from final_reporting_db.plan_change_facts cf join 
    final_reporting_db.plan_dim d 
-----^ where is the `on` clause ??? 
where d.id in(1,2,3,4,5,6,8,9,13) and 
     cf.date between '2016-04-24' and '2016-04-28' 
group by plan_date, type_name; 

我注意以下事項:

  • 子查詢的相關條件,什麼都不做,因爲他們是在子查詢比較的列。
  • 您錯過了最終加入的on子句,所以這是一個笛卡爾積。
  • 我懷疑你使用的是實現子查詢的MySQL。所以,你不需要在group by之前的子查詢。