简体   繁体   English

SQL Server,这是正确的索引用法吗?

[英]SQL Server, is this correct index usage?

I'm trying to get to grips with indexes. 我正在尝试掌握索引。 Given the table: 给定表:

Books
------
ID (PK)
Title
CategoryID (FK)
AuthorID (FK)

Where in my ASP.net pages, I have webpages that will fetch the books by author, or by category, would I create an index on CategoryID Asc, AuthorID asc if I wanted to improve retrieval times? 在ASP.net页面的哪个位置,有一些网页可以按作者或按类别提取书籍,如果我想缩短检索时间,可以在CategoryID Asc, AuthorID asc上创建索引吗?

Have I correctly understood it? 我正确理解了吗? If I use multiple columns as above, is that called a clustered index or is that something else? 如果我如上所述使用多个列,那是所谓的clustered index还是其他?

You should create two indexes, one for the CategoryID and one for the AuthorID . 您应该创建两个索引,一个用于CategoryID ,一个用于AuthorID Having both in the same index is not what you need if you look for one or the other; 如果要寻找一个另一个,则不需要两者都在同一索引中。 you'd need that if you were always querying for both at the same time (eg category and author). 如果您总是要同时查询两者(例如,类别和作者),则需要使用。

A clustered index controls the physical order of the data. 聚集索引控制数据的物理顺序。 Usually, if you have an identity column, using it as clustered index (which the primary key by default is) is just fine. 通常,如果您有一个身份列,则将其用作聚簇索引(默认情况下,主键为聚簇索引)就可以了。

A clustered index means the data is stored in the table and on disk (etc.) in the order the index specifies. 聚集索引意味着数据按照索引指定的顺序存储在表和磁盘(等)中。 A consequence of this is, that only one clustered index can exist. 其结果是,只能存在一个聚集索引。

The index CategoryID Asc, AuthorID asc will make lookups on specific categories faster, and lookups on specific categories with specific authors would be ideal. 索引CategoryID Asc, AuthorID asc将使对特定类别的查找更快,并且对具有特定作者的特定类别的查找将是理想的。 But it is not ideal for author lookups alone because you will have to find authors for every category. 但是,仅对作者查找并不理想,因为您必须为每个类别查找作者。 In that case two separate indexes would be better. 在这种情况下,两个单独的索引会更好。

The appropriate index would depends on what the query does. 适当的索引将取决于查询的作用。 If you have a query joining against both category and author, then you may have use for an index with both fields, otherwise you may have more use for two separate indexes. 如果您有一个同时针对类别和作者的查询,那么您可能会同时使用两个字段的索引,否则可能会更多地使用两个单独的索引。

A clustered index is an index that decides the storage order of the records in the table, and has nothing to do with the number of fields it contains. 聚集索引是决定表中记录存储顺序的索引,与它包含的字段数无关。 You should already have a clustered index on the primary key, so you can't create another clustered index for that table. 您应该已经在主键上具有聚簇索引,因此您不能为该表创建另一个聚簇索引。

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

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