2012-03-19 55 views
1

我有一個頁面,它需要太長時間才能加載,因爲它必須計算每個類別中成員的數量。 http://www.storeboard.com/counties/default.asp?cou=1196更快的SQL計數

經進一步調查,我偶然發現這個頁面:http://blogs.msdn.com/b/martijnh/archive/2010/07/15/sql-server-how-to-quickly-retrieve-accurate-row-count-for-table.aspx

我的問題是我如何改變這樣的:在我引用的頁面的解決方案4

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 

走進建議。

任何幫助,您可以提供將不勝感激。

非常感謝,保羅

+3

爲表這些例子查詢對象/索引級統計的MemberIds,你不能給他們應用一個條件 - 你的示例頁面看起來像是希望爲每個類別計算X,但是你的查詢示例似乎並不適用於它們的集合,那麼你使用的整個sql – 2012-03-19 17:15:18

回答

2

如果你真的需要搜索所有這些領域,然後對其進行索引適當 - 使用探查器和數據庫引擎優化顧問的一個很好的起點。

一種替代方法是將這10個NYKACatIDExtra字段提取到單獨的表中,並將它們排列爲一對多關係。然後使用加入找到物品的類別和計數應該更快...

3

你必須規範你的數據庫,即移動NYKACatID,NYKACatIDExtra1 .. NYKACatIDExtra10到單獨的表。爲該表定義適當的索引並使用連接重寫你的查詢。

+1

正如Vitaliy所述,你真正的問題是您已經對數據模型進行了非規範化。現在你必須使用一系列的OR。 OR使DBMS很難使用索引。解決這個問題,你的表現問題也會消失。您不必規範化數據模型。您可以調整SQL,使其可以在未規範化的數據模型上工作(如您所示)。但這將是困難和緩慢的。使用Flow,SQL在規範化的數據模型上效果最佳。 – Wim 2012-03-19 17:54:56

-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會讓獨特

+0

不幸的是,這證明比我的解決方案更慢。 – neojakey 2012-03-19 18:35:03

+0

@neojakey您需要在這些列上單獨使用「包含列的已過濾索引」來利用此方法; '在成員(nykacountyid,nycacatidextra1)上創建非聚集索引ix_m_nykacid_nykacide1 include(memberid)其中profiletypeid <> 1'(其中10個) – 2012-03-19 18:49:17