避免来自sql查询的子查询

时间:2010-12-08 12:21:28

标签: sql-server-2005

我有这样的查询:

SELECT emppayslipgenerationdetails.EMPpayslipgenerationdetailid,
       emppayslipgenerationdetails.MonthNumber                 ,
       emppayslipgenerationdetails.YearNumber                  ,
       emppayslipgenerationdetails.FinancialYearID             ,
       emppayheadvalues.PayHeadMasterID                        ,
       emppayheadvalues.PayHeadValue                           ,
       ISNULL(
       ( SELECT  SUM(EPH.PayHeadValue) AS YTD
       FROM     emppayheadvalues EPH
       WHERE    EPH.EmppayslipgenerationdetailID<=emppayslipgenerationdetails.EMPpayslipgenerationdetailid
       AND      EPH.PayHeadMasterID              =emppayheadvalues.PayHeadMasterID
       AND      EmppayslipgenerationdetailID IN
                (SELECT EmppayslipgenerationdetailID
                FROM    emppayslipgenerationdetails
                WHERE   FinancialYearID=2
                AND     EmpNumber      ='E0012'
                )
       GROUP BY PayheadMasterID
       )
       ,0)AS YTD
FROM   emppayheadvalues
       INNER JOIN emppayslipgenerationdetails
       ON     emppayheadvalues.EMPpayslipgenerationdetailid= emppayslipgenerationdetails.EMPpayslipgenerationdetailid
WHERE  emppayslipgenerationdetails.empnumber               ='E0012'
AND    emppayslipgenerationdetails.FinancialYearID         =2

如何删除影响性能的子查询

1 个答案:

答案 0 :(得分:0)

消除子查询的一般方法是使用join。

为了证明这一点 - 要消除最内在的查询,你应该尝试或多或少的事情:

   SELECT   SUM(EPH.PayHeadValue) AS YTD
   FROM     emppayheadvalues EPH
   JOIN     emppayslipgenerationdetails
   WHERE    EPH.EmppayslipgenerationdetailID<=emppayslipgenerationdetails.EMPpayslipgenerationdetailid
   AND      EPH.PayHeadMasterID              =emppayheadvalues.PayHeadMasterID
   AND      EmppayslipgenerationdetailID     =emppayslipgenerationdetails.EmppayslipgenerationdetailID
   AND      EmpNumber                        ='E0012'
   AND      emppayslipgenerationdetails.FinancialYearID=2
   GROUP BY PayheadMasterID

但请注意,在某些情况下,这可能比子查询更昂贵。