为什么在使用比较运算符时使用索引扫描而不是查找

时间:2018-11-03 20:55:57

标签: sql-server tsql query-optimization query-planner

数据库Sales.SalesOrderDetail中有一个表AdventureWorks2014

我有两个查询:

--Query 1 uses index IX_SalesOrderDetail_ProductID
SELECT
sod.SalesOrderID
FROM Sales.SalesOrderDetail sod
WHERE sod.SalesOrderID = 1

和:

--Query 2 uses index PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID
SELECT
sod.SalesOrderID
FROM Sales.SalesOrderDetail sod
WHERE sod.SalesOrderID > 1

查询计划: enter image description here

The query plan at Brentozar.com can be seen here.

和索引:

CREATE NONCLUSTERED INDEX [IX_SalesOrderDetail_ProductID] ON [Sales]. 
[SalesOrderDetail]
(
    [ProductID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
    DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, 
    ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

和聚集索引如下:

ALTER TABLE [Sales].[SalesOrderDetail] ADD  CONSTRAINT 
[PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED 
(
    [SalesOrderID] ASC,
    [SalesOrderDetailID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, 
    ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

我的问题是为什么查询优化器更喜欢另一个索引 PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID 而不是IX_SalesOrderDetail_ProductID

1 个答案:

答案 0 :(得分:1)

好吧,我的意思是,您正在选择 all 行(可能是其中之一)。在这里,搜索和扫描之间确实没有区别。 SQL Server选择对最窄的索引执行一次扫描,而不是执行80,000次搜索(或者表中有很多订单)。

寻求并不总是最好的选择,但这是一个常见的误解。实际上,有时您绝对想要进行扫描。