2014-10-02 95 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