更快的SQL计数

时间:2012-03-19 17:10:45

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

我有一个页面,加载时间太长,因为它必须计算每个类别中的成员数量。 http://www.storeboard.com/counties/default.asp?cou=1196

经过进一步调查,我偶然发现了这个页面:http://blogs.msdn.com/b/martijnh/archive/2010/07/15/sql-server-how-to-quickly-retrieve-accurate-row-count-for-table.aspx

我的问题是如何更改此内容:

SELECT COUNT(MemberID) AS MembersInCountyCat
FROM Member
WHERE NYKACountyID = @NYKACountyID
AND (
    NYKACatID = @NYKACatID 
 OR NYKACatIDExtra1 = @NYKACatID 
 OR NYKACatIDExtra2 = @NYKACatID 
 OR NYKACatIDExtra3 = @NYKACatID 
 OR NYKACatIDExtra4 = @NYKACatID 
 OR NYKACatIDExtra5 = @NYKACatID
 OR NYKACatIDExtra6 = @NYKACatID 
 OR NYKACatIDExtra7 = @NYKACatID 
 OR NYKACatIDExtra8 = @NYKACatID 
 OR NYKACatIDExtra9 = @NYKACatID 
 OR NYKACatIDExtra10 = @NYKACatID
)
AND ProfileTypeID <> 1

进入我引用的页面解决方案4中的建议。

非常感谢您提供的任何帮助。

很多,谢谢,保罗

3 个答案:

答案 0 :(得分:3)

你必须规范你的数据库,即将NYKACatID,NYKACatIDExtra1 .. NYKACatIDExtra10移动到单独的表中。为该表定义正确的索引,并使用join重写您的查询。

答案 1 :(得分:2)

如果您确实需要搜索所有这些字段,请对其进行适当的索引 - 使用Profiler和数据库引擎优化顾问来获得良好的起点。

另一种方法是将这10个NYKACatIDExtra字段提取到一个单独的表中,并将它们排列为一对多关系。然后使用join来查找项目的类别,并且计数应该快得多......

答案 2 :(得分:-1)

这样的事情可能是为了利用索引(如果你有的话):

select MembersInCountyCat = count(*) 
from (
SELECT MemberID
FROM Member
WHERE NYKACountyID = @NYKACountyID
AND NYKACatID = @NYKACatID
AND ProfileTypeID <> 1 
union
SELECT MemberID
FROM Member
WHERE NYKACountyID = @NYKACountyID
AND NYKACatIDExtra1 = @NYKACatID 
AND ProfileTypeID <> 1
union
...
union 
SELECT MemberID
FROM Member
WHERE NYKACountyID = @NYKACountyID
AND NYKACatIDExtra10 = @NYKACatID 
AND ProfileTypeID <> 1
) t

union会使这些MemberIds成为唯一

相关问题