📅  最后修改于: 2020-11-17 03:35:21             🧑  作者: Mango
聚集索引和非聚集索引之间的差异是数据库相关访谈中最著名的问题。这两个索引具有相同的物理结构,并作为BTREE结构存储在MySQL服务器数据库中。在本节中,我们将解释它们之间最流行的差异。
MySQL中的索引编制是一个过程,可帮助我们非常快速地从表中返回请求的数据。如果该表没有索引,它将在整个表中扫描请求的数据。 MySQL允许两种不同类型的索引:
让我们首先简要讨论聚簇索引和非聚簇索引。
聚集索引是用于存储行数据的表。它基于只能在一个方向上排序的键值定义表数据的顺序。在数据库中,每个表只能包含一个聚集索引。在关系数据库中,如果表列包含主键或唯一键,则MySQL允许您基于该特定列创建名为PRIMARY的聚集索引。
以下示例说明了如何在MySQL中创建聚簇索引:
CREATE TABLE Student
( post_id INT NOT NULL AUTO_INCREMENT, user_id INT NOT NULL,
CONSTRAINT Post_PK
PRIMARY KEY (user_id, post_id), //clustered index
CONSTRAINT post_id_UQ
UNIQUE (post_id)
) ENGINE = InnoDB ;
以下是聚集索引的基本特征:
除PRIMARY索引(聚集索引)以外的索引称为非聚集索引。非聚集索引也称为二级索引。非聚集索引和表数据都存储在不同的位置。它不能对表数据进行排序(排序)。非聚集索引与将内容写在一个地方的书相同,而索引在另一个地方。 MySQL允许一个表存储一个或多个非聚集索引。非聚集索引可提高使用键而不分配主键的查询的性能。
//It will create non-clustered index
CREATE NonClustered INDEX index_name ON table_name (column_name ASC);
以下是非聚集索引的基本特征:
让我们通过表格形式查看聚集索引和非聚集索引之间的一些常见差异:
Parameter | Clustered Index | Non-Clustered Index |
---|---|---|
Definition | A clustered index is a table where the data for the rows are stored. In a relational database, if the table column contains a primary key, MySQL automatically creates a clustered index named PRIMARY. | The indexes other than PRIMARY indexes (clustered indexes) called a non-clustered index. The non-clustered indexes are also known as secondary indexes. |
Use for | It can be used to sort the record and store the index in physical memory. | It creates a logical ordering of data rows and uses pointers for accessing the physical data files. |
Size | Its size is large. | Its size is small in comparison to a clustered index. |
Data Accessing | It accesses the data very fast. | It has slower accessing power in comparison to the clustered index. |
Storing Method | It stores records in the leaf node of an index. | It does not store records in the leaf node of an index that means it takes extra space for data. |
Additional Disk Space | It does not require additional reports. | It requires an additional space to store the index separately. |
Type of Key | It uses the primary key as a clustered index. | It can work with unique constraints that act as a composite key. |
Contains in Table | A table can only one clustered index. | A table can contain one or more than a non-clustered index. |
Index Id | A clustered index always contains an index id of 0. | A non-clustered index always contains an index id>0. |