简体   繁体   English

查询未执行索引查找或扫描

[英]Query not doing index seek or scan

I am fairly new to Indexes. 我是Index的新手。 I have table following table [FORUM1] 我有下面的表格[FORUM1]

    [msg_id] [int] IDENTITY(1,1) NOT NULL,
    [cat_id] [int] NULL,
    [msg_title] [nvarchar](255) NULL

And have created a non clustered index 并创建了非聚集索引

CREATE NONCLUSTERED INDEX catindex ON forum1(cat_id)

Now when i run this simple query, i can see index is not being used 现在,当我运行此简单查询时,我可以看到未使用索引

SELECT msg_title FROM forum1 where cat_id=4

Index only gets called if i create CI and include the MSG_TITLE fld. 仅当我创建CI并包含MSG_TITLE fld时才调用索引。 But the issue is that i have to run many more similar queries on actually table like date=something, userid=20, status=1. 但是问题是我必须在实际表上运行更多类似的查询,例如date = something,userid = 20,status = 1。 So including columns in every index doesn't good to me . 因此,在每个索引中都包含列对我不利。

执行计划屏幕截图

The msg_title is not contained in the index -> any value found in the non-clustered index will need a key lookup into the actual data pages, which is an expensive operation - so therefore, most likely, a table scan is quicker. msg_title不包含在索引中->在非聚簇索引中找到的任何值都需要在实际数据页中进行键查找 ,这是一项昂贵的操作 -因此,最有可能的是,表扫描更快。 Plus: the "table scan" indicates you have a heap - a table without a clustered index - which is a bad thing (most of the time) to begin with. 另外:“表扫描”表明您有一个堆-一个没有聚簇索引的表-开始时(在大多数情况下)这很不好。 Why don't you have a clustered index? 为什么没有聚簇索引?

You can fix this by eg including the msg_title in your index: 您可以通过在索引中包含 msg_title来解决此问题:

CREATE NONCLUSTERED INDEX catindex 
ON forum1(cat_id) INCLUDE(msg_title)

and now, I'm pretty sure, SQL Server will use that index (since it can find all the data needed for the query in the index structure - the index is said to be a covering index ). 现在,我非常确定,SQL Server将使用该索引(因为它可以在索引结构中找到查询所需的所有数据-据说该索引是覆盖索引 )。 The benefit here is: the extra column is only included in the leaf level of the index, so it makes the index only minimally bigger. 这样做的好处是:额外的列仅包含在索引的叶级别中,因此它仅使索引最小。 Yet, it can lead to the index being used just all that more often. 但是,它可能导致索引被更频繁地使用。 Well worth it! 非常值得!

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

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