SQL查询花了10多分钟

时间:2013-06-11 08:23:39

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

以下查询花费了太多时间(超过10分钟)。有没有办法让它更快?

select  r.id,rs1.Id,  rs2.Id
  from Resource rs1 , Resource rs2 , ResourceTerritory rst1 ,
 ResourceTerritory rst2 ,
 ReleaseResource rr1 , 
 ReleaseResource rr2 , Release r
 where
rs1.Id=rst1.ResourceId and rs2.Id=rst2.ResourceId and rs1.Id=rr1.ResourceId and rs2.Id=rr2.ResourceId
and rr1.ReleaseId=rr2.ReleaseId 
and rs1.Id<>rs2.id
and rs1.OwningTerritoryId=69 and rs2.OwningTerritoryId=200
and r.Id=rr1.ReleaseId and r.OwningTerritoryId=69 and rs1.IsLocked=0 and rs2.IsLocked=0
group by   r.id,rs1.Id,  rs2.Id
having SUM( case when rst1.TerritoryId = 62 then 1 else 0 end)>0 and 
SUM( case when rst1.TerritoryId = 69 then 1 else 0 end)>0 and
SUM( case when rst1.TerritoryId = 200 then 1 else 0 end)>0 and 
SUM( case when rst1.TerritoryId = 201 then 1 else 0 end)>0 and
SUM( case when rst2.TerritoryId = 69 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 62 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 200 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 201 then 1 else 0 end)=0 

3 个答案:

答案 0 :(得分:0)

你有索引(例如) TerritoryId

同时检查:http://msdn.microsoft.com/en-us/library/ms345434.aspx

并运行SQL Server Profiler(在“工具”菜单下)

而不是WHERE子句,您可以使用INNER JOIN子句

答案 1 :(得分:0)

having SUM( case when rst1.TerritoryId = 62 then 1 else 0 end)>0 and 
SUM( case when rst1.TerritoryId = 69 then 1 else 0 end)>0 and
SUM( case when rst1.TerritoryId = 200 then 1 else 0 end)>0 and 
SUM( case when rst1.TerritoryId = 201 then 1 else 0 end)>0 and
SUM( case when rst2.TerritoryId = 69 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 62 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 200 then 1 else 0 end)>0  and 
SUM( case when rst2.TerritoryId = 201 then 1 else 0 end)=0 

应替换为

WHERE 
(rst1.TerritoryId = 62 
OR rst1.TerritoryId = 69 
OR rst1.TerritoryId = 200 
OR rst1.TerritoryId = 201) 
AND 
(rst2.TerritoryId = 62 
OR rst2.TerritoryId = 69 
OR rst2.TerritoryId = 200 
)

答案 2 :(得分:0)

尝试这样的事情 -

SELECT  r.ID
        ,rs1.ID
        ,rs2.ID 
FROM dbo.Release r
JOIN dbo.[Resource] rs1 ON r.ID = rr1.ReleaseId AND rs1.IsLocked = 0
JOIN dbo.ResourceTerritory rst1 ON rs1.ID = rst1.ResourceId
JOIN dbo.[Resource] rs2 ON rs2.IsLocked = 0
JOIN dbo.ResourceTerritory rst2 ON rs2.ID = rst2.ResourceId
JOIN dbo.ReleaseResource rr1 ON rs1.ID = rr1.ResourceId 
JOIN dbo.ReleaseResource rr2 ON rr1.ReleaseId = rr2.ReleaseId
WHERE rs2.ID = rr2.ResourceId
    AND rs1.ID <> rs2.ID
    AND rs1.OwningTerritoryId = 69
    AND rs2.OwningTerritoryId = 200
    AND r.OwningTerritoryId = 69
    AND rst1.TerritoryId IN (62, 69 , 200 , 201) 
    AND rst2.TerritoryId IN (62 , 69 , 200 , 201)
GROUP BY
    r.ID
    ,rs1.ID
    ,rs2.ID
相关问题