2014-10-02 93 views
1

我持有上出現了一次事件,如史表:的SQL Server索引設計

EventType | OccurredOn  | Other.. | Data.. 
-------------------------------------------- 
1   | 2014/10/02 09:00 | foo  | bar 
1   | 2014/10/02 10:00 | foo  | bar 
2   | 2014/10/03 09:00 | foo  | bar 
1   | 2014/10/04 09:00 | foo  | bar 
3   | 2014/10/05 09:00 | foo  | bar 
2   | 2014/10/05 09:00 | foo  | bar 
4   | 2014/10/05 09:00 | foo  | bar 

我所有的問題在該表上會的形式爲:

select [OccurredOn], [OtherData] 
from [Data] 
where [EventType] = @type and [OccurredOn] between @start and @end 

也許與grouping和選擇聚合數據。

行會按時間順序幾乎總是被插入,當他們被插入了時間順序,將OccurredOn應該是合理的「近期」 - 即不太遠之前已經插入了「最新」行

應該如何我把這個表格索引爲有效選擇?

大概我的PK應該是聚簇的,並且包括OccurredOn它,但是沒有天然的唯一鍵,所以大概我需要一個autoincrement int的列呢?

更新

行而言,該表將有幾百萬,可能是數以百萬計10S

我使用SQL Server 208R2

+3

首先,[不要使用'BETWEEN'進行日期範圍查詢](http://sqlblog.com/blogs/aaron_bertrand/archive/2011/10/19/what-do-between-and-the-devil-have-in-common.aspx) 。 – 2014-10-02 16:51:45

+0

感謝protip – 2014-10-02 16:53:56

回答

0

的第一件事 - OccurredOn時間可以有重複的值。

從以下開始並分析執行計劃以稍後調整它。

我建議添加一個代理/代理鍵,這是一個自動增量標識列 - 讓我們將其命名爲「NewColumn」。保留這個「NewColumn」爲Primary Key。將主鍵保留爲Non-Clustered

使用列(OccurredOn,NewColumn)創建Unique Clustered Index。這種聚集索引有助於日期範圍搜索。

保持羣集索引上的「OccurredOn」有助於保持羣集索引不斷增加的順序。

保持NewColumn與OccurredOn一起,有助於使聚簇索引具有唯一性。這有助於避免SQL Server的增加本身就是一個唯一標誌(非唯一聚集索引的情況下)

參考

  1. Is it needed to add additional column to make this clustered index unique?
  2. Clustered index on random order column