2013-07-13 164 views
2

我希望你们能帮助我。我有以下SQL查询,我认为它不是很重,但大约需要5分钟才能完成。请让我知道,如果你有另一种方式来完成这一点:加速SQL查询嵌套查询

update rep 
set rep.StatusID= 2, 
rep.Available= 1, 
rep.User= @user 
from dbo.MCP_Rep_Compensation_Plan rep 
left join dbo.MCP_Compensation_Plan compensationplan on compensationplan.Compensation_Plan_ID = @compplan_id and compensationplan.Active = 1 
left join dbo.MRRS_Cycle actualcycle on actualcycle.CycleID = compensationplan.CycleID and actualcycle.Active = 1 
left join dbo.MRRS_Cycle lastcycle on lastcycle.Consecutive = actualcycle.Consecutive -1 and lastcycle.Active = 1 
where rep.Active = 1 and rep.ID_Compensation_Plan = @compplan_id and exists(
select OrderID 
from dbo.MCP_Orders 
where Active = 1 and Order_cycle = lastcycle.CycleID and OrderRepID = rep.RepID 
and Order_Status in(28,30)) 
+0

难道你看执行计划? –

+0

你有合适的索引吗? –

回答

2

我看到有些地方你的查询可以被改写,但我不知道会有多大帮助不看你的执行计划,并确保你有适当的指数。

例如,确保您在第一次加入补偿计划表时包含实际加入标准。通过加入compensationplan.Compensation_Plan_IDrep.ID_Compensation_Plan来完成此操作。

此外,我没有看到OUTER JOINs的需要,因为您正在使用您的相关存在的子查询中的一些表。

这里是更新查询:

update rep 
    set rep.StatusID= 2, 
    rep.Available= 1, 
    rep.User= @user 
from dbo.MCP_Rep_Compensation_Plan rep 
    join dbo.MCP_Compensation_Plan compensationplan on 
     compensationplan.Compensation_Plan_ID = rep.ID_Compensation_Plan and compensationplan.Active = 1 
    join dbo.MRRS_Cycle actualcycle on 
      actualcycle.CycleID = compensationplan.CycleID and actualcycle.Active = 1 
    join dbo.MRRS_Cycle lastcycle on 
      lastcycle.Consecutive = actualcycle.Consecutive -1 and lastcycle.Active = 1 
where rep.Active = 1 
    and rep.ID_Compensation_Plan = @compplan_id 
    and exists(
     select OrderID 
     from dbo.MCP_Orders 
     where Active = 1 
      and Order_cycle = lastcycle.CycleID 
      and OrderRepID = rep.RepID 
      and Order_Status in(28,30) 
    ) 
+0

我必须说,与您的查询和重新检查我的索引(如您的评论说),查询从5分钟改善到不到10secs。 –