在SELECT和HAVING语句中使用COUNT优化T-SQL查询

时间:2015-11-05 16:57:36

标签: sql sql-server tsql join optimization

我不确定这是否与我处理非常大的表(有些有9亿多行)的事实有关,但我在优化查询时遇到了问题。我已经检查并尽可能使用索引字段,我的查询中使用的大多数字段实际上都被索引。使用select top 100语句大约需要10分钟,我希望得到所有结果,很多更多更快。我将如何优化此查询和未来的查询呢?出于安全考虑,我不得不在下面使用替代别名:

SELECT TOP 100 
    x.ID, j.ID, j.FirstDate, j.ExpiryDate, x.Lock, COUNT (*) as Numbers
FROM
   j WITH(NOLOCK)
INNER JOIN   
   jp WITH(NOLOCK) ON j.ID = jp.ID
INNER JOIN   
   jd WITH(NOLOCK) ON (jd.ID = jp.ID And jd.path = 3)
INNER JOIN  
   fa WITH(NOLOCK) ON fa.ID = j.ID
INNER JOIN  
   l WITH(NOLOCK) ON j.ID = l.ID AND l.CoID = 3
INNER JOIN   
   c WITH(NOLOCK) ON c.CID = fa.CID
INNER JOIN  
   x WITH(NOLOCK) ON c.CID = x.CID
WHERE  
   j.ExpiryDate > GETDATE()
GROUP BY 
   x.ID, j.ID, j.FirstDate, j.ExpiryDate, x.Lock
HAVING 
   COUNT(*) <= 10

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT TOP 100 
    x.ID, j.ID, j.FirstDate, j.ExpiryDate, x.Lock, COUNT (*) as Numbers
FROM
   j WITH(NOLOCK)
INNER JOIN   
   jp WITH(NOLOCK) ON j.ID = jp.ID 
                  and j.ExpiryDate > GETDATE()
INNER JOIN   
   jd WITH(NOLOCK) ON (jd.ID = jp.ID And jd.path = 3)
INNER JOIN  
   fa WITH(NOLOCK) ON fa.ID = j.ID
INNER JOIN  
   l WITH(NOLOCK) ON j.ID = l.ID AND l.CoID = 3
INNER JOIN   
   c WITH(NOLOCK) ON c.CID = fa.CID
INNER JOIN  
   x WITH(NOLOCK) ON c.CID = x.CID      
GROUP BY 
   x.ID, j.ID, j.FirstDate, j.ExpiryDate, x.Lock
HAVING 
   COUNT(*) <= 10

答案 1 :(得分:0)

有时,有助于减少派生表中的数据集,然后仅对满足where条件的数据应用该函数。没有看到两者的破坏计划,我不知道它会起作用,但它值得一试。

SELECT  a.XID, a.JID, a.FirstDate, a.ExpiryDate, a.Lock, COUNT (*) as Numbers
FROM (
SELECT 
    x.ID as XID, j.ID as JID, j.FirstDate, j.ExpiryDate, x.Lock
FROM
   j 
INNER JOIN   
   jp  ON j.ID = jp.ID
INNER JOIN   
   jd  ON (jd.ID = jp.ID And jd.path = 3)
INNER JOIN  
   fa  ON fa.ID = j.ID
INNER JOIN  
   l ON j.ID = l.ID AND l.CoID = 3
INNER JOIN   
   c  ON c.CID = fa.CID
INNER JOIN  
   x ON c.CID = x.CID
WHERE  
   j.ExpiryDate > GETDATE()) a
GROUP BY 
  a.XID, a.JID, a.FirstDate, a.ExpiryDate, a.Lock
HAVING 
   COUNT(*) <= 10