2015-06-22 50 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