SQL Server Query Optimization - MultiJoins in table of 20 million records

时间:2017-04-24 17:31:31

标签: sql-server

Below mentioned query is run against tables which have huge number of records - upto 22029464.... And this is taking on an average around 20-25 mins in execution. Is there any scope of optimizing or rewriting this in different. Required indexes exist on all table, query plan show no missing index requirement

SELECT  stg.*
    FROM    dbo.s_NIIT_ResultValues stg
    WHERE   stg.resultId IN ( SELECT    resultId
                              FROM      Data_NIIT.dbo.NIIT_Results )
            AND ( stg.resultIntValueId IS NULL
                  OR stg.resultIntValueId IN (
                  SELECT    resultIntValueId
                  FROM      Data_NIIT.dbo.NIIT_ResultIntValues )
                )
            AND ( stg.resultBoolValueId IS NULL
                  OR stg.resultBoolValueId IN (
                  SELECT    resultBoolValueId
                  FROM      Data_NIIT.dbo.NIIT_ResultBoolValues )
                )
            AND ( stg.resultStringValueId IS NULL
                  OR stg.resultStringValueId IN (
                  SELECT    resultStringValueId
                  FROM      Data_NIIT.dbo.NIIT_ResultStringValues )
                )

1 个答案:

答案 0 :(得分:0)

我的第一个问题是“你为什么一次需要这么多记录?”为什么不使用分页。

其次请使用“with(nolock)”,不要使用“*”,请提及列名。

第三,我将我的联接改为左或使用“存在条款”。

SELECT  stg.mentioncolumnname,stg.mentioncolumnname1
    FROM    dbo.s_NIIT_ResultValues stg with (nolock)
where exists(SELECT    resultId
               FROM  Data_NIIT.dbo.NIIT_Results with (nolock)
                 where resultId=stg.resultId)
and exists(

  SELECT    resultBoolValueId
                  FROM  Data_NIIT.dbo.NIIT_ResultBoolValues with (nolock)
                  where ((stg.resultBoolValueId IS NULL) or (resultBoolValueId=stg.resultBoolValueId))
 )
 and exists(

  SELECT    resultStringValueId
                  FROM  Data_NIIT.dbo.NIIT_ResultStringValues with (nolock)
                  where ((stg.resultStringValueId IS NULL) or (resultStringValueId=stg.resultStringValueId ))
 )

另一种方式:与表dbo.s_NIIT_ResultValues有3​​个连接。

在3 diff编辑器中只使用dbo.s_NIIT_ResultValues连接一个表,并查看哪个结果集最小并告诉我们。