COUNT DISTINCT(列)使查询速度减慢20倍

时间:2015-06-22 06:12:33

标签: sql sql-server

我有查询,工作正常且速度很快(约1秒执行时间):

array.emplace_back();

但是一旦我将第二行更改为:

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

查询正在减慢 20X 次。 ,COUNT(DISTINCT LOGIN) AS number_of_accounts 这么慢是否会影响整个查询,或者我在这里遗漏了什么?

2 个答案:

答案 0 :(得分:1)

经过一些研究后我发现使用子查询有时比COUNT(DISTINCT column)更好。 所以这是我的查询,比我问题上的查询快20倍:

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

@Raphaël-Althau 感谢您提供有用的网址提示

答案 1 :(得分: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