【发布时间】:2011-05-28 01:27:58
【问题描述】:
我发现,在具有适当索引的索引视图上,MAX(date) 执行整个索引扫描,然后执行流聚合,而 TOP (1) date 以最佳方式使用索引并且仅扫描单行。对于大量行,这会导致严重的性能问题。我已经包含了一些代码来演示下面的问题,但我很想知道其他人是否可以解释为什么会发生这种行为(它不会发生在具有相似索引的表上)以及它是否是 SQL Server 优化器中的错误(我已经在 2008 SP2 和 R2 上进行了测试,并且都显示了相同的问题)。
CREATE TABLE dbo.TableWithDate
(
id INT IDENTITY(1,1) PRIMARY KEY,
theDate DATE NOT NULL
);
CREATE NONCLUSTERED INDEX [ix_date] ON dbo.TableWithDate([theDate] DESC);
INSERT INTO dbo.TableWithDate(theDate) VALUES('1 MAR 2010'),('1 MAR 2010'), ('3 JUN 2008');
-- Test 1: max vs top(1) on the table. They give same optimal plan (scan one row from the index, since index is in order)
SELECT TOP(1) theDate FROM dbo.TableWithDate ORDER BY theDate DESC;
SELECT MAX(theDate) FROM dbo.TableWithDate;
CREATE TABLE dbo.TheJoinTable
(
identId INT IDENTITY(1,1) PRIMARY KEY,
foreignId INT NOT NULL,
someValue INT NOT NULL
);
CREATE NONCLUSTERED INDEX [ix_foreignValue] ON dbo.TheJoinTable([foreignId] ASC);
INSERT INTO dbo.TheJoinTable(foreignId,someValue) VALUES (1,10),(1,20),(1,30),(2,5),(3,6),(3,10);
GO
CREATE VIEW dbo.TheTablesJoined
WITH SCHEMABINDING
AS
SELECT T2.identId, T1.id, T1.theDate, T2.someValue
FROM dbo.TableWithDate AS T1
INNER JOIN dbo.TheJoinTable AS T2 ON T2.foreignId=T1.id
GO
-- Notice the different plans: the TOP one does a scan of 1 row from each and joins
-- The max one does a scan of the entire index and then does seek operations for each item (less efficient)
SELECT TOP(1) theDate FROM dbo.TheTablesJoined ORDER BY theDate DESC;
SELECT MAX(theDate) FROM dbo.TheTablesJoined;
-- But what about if we put an index on the view? Does that make a difference?
CREATE UNIQUE CLUSTERED INDEX [ix_clust1] ON dbo.TheTablesJoined([identId] ASC);
CREATE NONCLUSTERED INDEX [ix_dateDesc] ON dbo.TheTablesJoined ([theDate] DESC);
-- No!!!! We are still scanning the entire index (look at the actual number of rows) in the MAX case.
SELECT TOP(1) theDate FROM dbo.TheTablesJoined ORDER BY theDate DESC;
SELECT MAX(theDate) FROM dbo.TheTablesJoined;
【问题讨论】:
-
这听起来更像是一个尚未在优化器中实现的功能,而不是一个错误。如果你使用
NOEXPAND表提示怎么办? -
只是出于好奇,如果在表之间声明外键会怎样?
-
如果我添加外键约束没有区别(我应该提到我已经尝试过)。但是,将 WITH (NOEXPAND) 添加到索引视图的查询确实会强制它选择不同的(最佳)计划。感谢您推荐我尝试一下。
标签: sql tsql sql-server-2008