SQl优化存在于何处

时间:2015-06-05 13:49:24

标签: sql sql-server sql-server-2008

正在查询的数据库包含几百万条记录 - 只是想知道以下查询是否可以进行优化

SELECT Count(DISTINCT [t0].[gUserId]) AS [UserId]
FROM [Plan] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [Entry] AS [t1]
    WHERE ([t1].[PlanId] = ([t0].[id])) 
    AND ([t1].[EntryMobile] = 1) AND (NOT ([t0].[Deleted] = 1)))

1 个答案:

答案 0 :(得分:0)

以下是另外两个与您的输出相同的查询:

1

SELECT Count(DISTINCT [t0].[gUserId]) AS [UserId]
    FROM [Plan] AS [t0]
        CROSS APPLY (SELECT TOP 1 1 X 
             FROM [Entry] AS [t1]
             WHERE [t1].[PlanId] = [t0].[id]
               AND [t1].[EntryMobile] = 1) t1
    WHERE [t0].[Deleted] <> 1

2

SELECT Count(DISTINCT [t0].[gUserId]) AS [UserId]
    FROM [Plan] AS [t0]
    WHERE [t0].[Deleted] <> 1
        AND [t0].[id] IN (SELECT [PlanId]
             FROM [Entry] 
             WHERE [EntryMobile] = 1)

我怀疑#2是最快的,但不是很多。

要进行测试,请在SQL Server Management Studio的单个SQL批处理中一起运行它们,并设置“包含实际执行计划”选项,然后比较执行计划以查看哪个是最佳的。有时它会告诉你索引是否缺失。