2015-06-22 76 views
2

我有這個查詢的正常工作和快(1秒左右的執行時間):COUNT DISTINCT(列)減慢查詢20X

SELECT COUNT(ticket) AS times_appears 
    ,COUNT(LOGIN) AS number_of_accounts 
    ,comment 
FROM mt4_trades 
WHERE COMMENT != '' 
    AND CLOSE_TIME != '1970-01-01 00:00:00.000' 
GROUP BY comment 
ORDER BY times_appears DESC 

,但只要我改變第二行:

,COUNT(DISTINCT LOGIN) AS number_of_accounts 

查詢放緩20X倍。 DISTINCT是如此緩慢,影響整個查詢或我在這裏丟失的東西?

+0

能否請您發表評論吼叫爲什麼你下調?這將有助於我理解我在這裏做錯了什麼。 – BlackM

+0

你能解釋一下你的問題嗎? –

+1

你有沒有試過分析你的查詢,看看是什麼造成的? –

回答

1

經過一番研究,我發現有時使用子查詢比COUNT(DISTINCT column)更好。 所以這是我查詢這是一個比我的問題更快的20X倍:

SELECT COUNT(mtt.ticket) as times_appears 
     --,COUNT(DISTINCT login) as number_of_accounts 
     ,(SELECT COUNT(LOGIN) FROM (SELECT DISTINCT login FROM mt4_trades WHERE COMMENT=mtt.COMMENT AND CLOSE_TIME != '1970-01-01 00:00:00.000') AS temp)AS number_of_accounts 
     ,comment 
FROM mt4_trades mtt 
WHERE mtt.COMMENT != '' 
AND mtt.CLOSE_TIME != '1970-01-01 00:00:00.000' 
GROUP BY mtt.comment 
ORDER BY times_appears DESC 

@拉斐爾 - Althau謝謝你的幫助的URL,暗示

0
---- tickt count, irrespective of login 
Select mtt.comment 
     ,t.number_of_accounts 
     ,Count(mtt.ticket) As times_appears 
From mt4_trades As mtt With (Nolock) 
     Join 
     (
      Select t.comment 
        ,Count(t.login) As number_of_accounts 
      From (
         Select Distinct 
           mtt.login 
           ,mtt.comment 
         From mt4_trades As mtt With (Nolock) 
         Where mtt.comment <> '' 
           And mtt.CLOSE_TIME <> '1970-01-01 00:00:00.000' 
        ) As t 
      Group By t.comment 
     ) As mt On mtt.comment = t.comment 
Where mtt.comment <> '' 
     And mtt.CLOSE_TIME <> '1970-01-01 00:00:00.000' 
Group By mtt.comment 
     ,t.number_of_accounts 

---- tickt count with respect to login 
Select t.comment 
     ,Count(t.ticket) As times_appears 
     ,Count(t.login) As number_of_accounts 
From (
      Select Distinct 
        mtt.ticket 
        ,mtt.login 
        ,mtt.comment 
      From mt4_trades As mtt With (Nolock) 
      Where mtt.comment <> '' 
        And mtt.CLOSE_TIME <> '1970-01-01 00:00:00.000' 
     ) As t 
Group By t.comment 
+0

感謝您的答覆,但第二個查詢返回相同的值'times_appears'和'number_of_accounts' 。我的查詢返回正確的值(與COUNT(DISTINCT列)相同'但如果你認爲它可以改進讓我知道) – BlackM