Mic*_*cah 2 t-sql indexing sql-server-2008
假设我有下表:
Orders
======
OrderID
CustomerID
StatusID
DateCreated
Run Code Online (Sandbox Code Playgroud)
我有以下疑问:
select CustomerID from Orders where OrderID = 100
select OrderID from Orders where CustomerID = 20
select OrderID, StatusID from Orders where CustomerID = 100 and OrderID = 1000
Run Code Online (Sandbox Code Playgroud)
如果我制作以下索引:
create nonclustered index Example
On dbo.Orders(OrderID,CustomerID)
Include(StatusID)
Run Code Online (Sandbox Code Playgroud)
这是否可以使用一个索引优化所有3个查询?换句话说,复合索引是否可以改进使用复合中其中一个项的查询?或者是否应该仅在这些列上创建单个索引(即OrderID,CustomerID)以满足查询1和2?
此索引将无法帮助第二个查询,因为无法首先在索引中最左侧的列上进行搜索.
想想电话簿.首先,尝试找到姓史密斯的所有人.容易,对吗?现在,尝试找到名字为John的所有人.电话簿中"索引"的工作方式是LastName,FirstName.当你试图找到所有的约翰时,首先按照LastName排序它们根本没有用 - 你仍然需要浏览整本电话簿,因为会有一个John Anderson和一个John Zolti以及介于两者之间的所有内容.
为了充分利用所有三个查询,并假设这些是正在使用的唯一三个查询表单,我可能会建议一个额外的索引:
create nonclustered index Example2
On dbo.Orders(CustomerID) INCLUDE(OrderID)
Run Code Online (Sandbox Code Playgroud)
(如果OrderID是主键,则不需要包含它.)
但是,这应该针对您的工作负载进行测试,因为索引不是免费的 - 它们确实需要额外的磁盘空间,并且在运行DML查询时需要维护额外的工作.而且,这假设您的问题中列出的三个查询是您使用的唯一形状.如果您有其他查询具有不同的输出列或不同的where子句,则所有投注都将关闭.