简体   繁体   English

索引如何减慢select语句的速度?

[英]How can an index slow down a select statement?

I am having quite a difficult time at finding why adding an index on the foreign key of a table is slowing down the view of my colleague. 我很难找到为什么在表的外键上添加索引会减慢我的同事的观点。 This view is composed of several packed views with outer join and inner join. 此视图由具有外连接和内连接的多个打包视图组成。 I tried to remove them one by one to figure out where the problem was, but I cannot say, it doesn't seem to come from a particular view but more from them all. 我试图逐一删除它们以找出问题所在,但我不能说,它似乎不是来自特定的视图,而是来自它们的更多。

I knew indexes could slow down insert or that they were taking size on the hard drive, but I never read anywhere that they could be responsible for slowing down a view. 我知道索引可以减慢插入速度或者它们在硬盘驱动器上占用大小,但我从来没有读过他们可能负责减慢视图的任何地方。 The truth is when I do : 事实就是我这样做:

DBCC FREEPROCCACHE
DBCC DROPCLEANBUFFERS
GO

select top 20 * from  MyView

It takes 20 seconds with the index and 9 without. 索引需要20秒而没有索引需要9秒。

CREATE NONCLUSTERED INDEX [IX_MyField] ON [dbo].MyTable
(
    [MyField] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, 
  IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON,
  ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]

It's possible your OTHER indexes or stats are out of date. 您的OTHER索引或统计信息可能已过期。 If they aren't current, it's possible the query analyzer is choosing a sub-optimal execution plan using your new index since it thinks that will be quicker. 如果它们不是最新的,查询分析器可能会使用您的新索引选择次优执行计划,因为它认为会更快。

Try running: 试试跑步:

UPDATE STATISTICS WITH (FULLSCAN)

on your table. 在你的桌子上。

Are you selecting any other columns from MyTable? 您是从MyTable中选择任何其他列吗? If so, you're probably doing a Bookmark Lookup (or RID Lookup), which means you're going to back to your table for the additional data. 如果是这样,您可能正在进行书签查找(或RID查找),这意味着您将返回表格以获取其他数据。

You should place any columns that you additionally select in the INCLUDE clause of the index. 您应该在索引的INCLUDE子句中放置您另外选择的任何列。

Run both queries with execution plans enabled and compare the 2, identifying which portions of the query take longer. 在启用执行计划的情况下运行两个查询并比较2,确定查询的哪些部分需要更长时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM