MySQL 彙集索引和二級索引

Clustered and Secondary Indexes(彙集索引和二級索引)

Every InnoDB table has a special index called the clustered index where the data for the rows is stored. Typically, the clustered index is synonymous with the primary key. To get the best performance from queries, inserts, and other database operations, you must understand how InnoDB uses the clustered index to optimize the most common lookup and DML operations for each table.數據庫

每張使用 InnoDB 做爲存儲引擎的表都有一個特殊的索引稱爲彙集索引,它保存着每一行的數據,一般,彙集索引就是主鍵索引。爲了獲得更高效的查詢、插入以及其餘的數據庫操做的性能,你必須理解 InnoDB 引擎是如何使用匯集索引來優化常見的查找和 DML 操做。性能

  • When you define a PRIMARY KEY on your table, InnoDB uses it as the clustered index. Define a primary key for each table that you create. If there is no logical unique and non-null column or set of columns, add a new auto-increment column, whose values are filled in automatically.
    若是你的表定義了一個主鍵,InnoDB 就使用它做爲彙集索引。所以,儘量的爲你的表定義一個主鍵,若是實在沒有一個數據列是惟一且非空的能夠做爲主鍵列,建議添加一個自動遞增列做爲主鍵列。優化

  • If you do not define a PRIMARY KEY for your table, MySQL locates the first UNIQUE index where all the key columns are NOT NULL and InnoDB uses it as the clustered index.
    若是你的表沒有定義主鍵,InnoDB 會選擇第一個惟一非空索引來做爲彙集索引。ui

  • If the table has no PRIMARY KEY or suitable UNIQUE index, InnoDB internally generates a hidden clustered index named GEN_CLUST_INDEX on a synthetic column containing row ID values. The rows are ordered by the ID that InnoDB assigns to the rows in such a table. The row ID is a 6-byte field that increases monotonically as new rows are inserted. Thus, the rows ordered by the row ID are physically in insertion order.
    若是你的表既沒有主鍵,又沒有合適的惟一索引,InnoDB 內部會生成一個隱式彙集索引 —— GEN_CLUST_INDEX,該索引創建在由 rowid 組成的合成列上。數據行根據 InnoDB 分配的 rowid 排序,rowid 是一個 6 字節的字段,隨着數據插入而單調遞增。也就是說,數據行根據 rowid 排序其實是根據插入順序排序。this

How the Clustered Index Speeds Up Queries(彙集索引如何提高查詢效率)

Accessing a row through the clustered index is fast because the index search leads directly to the page with all the row data. If a table is large, the clustered index architecture often saves a disk I/O operation when compared to storage organizations that store row data using a different page from the index record.
經過彙集索引來訪問一行數據是很是快的,這是由於全部的行數據和索引在同一頁上。若是表特別大,相較於行數據和索引在不一樣頁上存儲結構(好比 myisam 引擎),這將大大節省磁盤 I/O 資源。spa

How Secondary Indexes Relate to the Clustered Index(二級索引和彙集索引如何關聯)

All indexes other than the clustered index are known as secondary indexes. In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index. InnoDB uses this primary key value to search for the row in the clustered index.
除了彙集索引外的其餘索引類型都屬於二級索引。在 InnoDB 中,二級索引中的每一個記錄都包含該行的主鍵列,以及二級索引指定的列;彙集索引中,InnoDB 經過主鍵值來查詢數據行。orm

If the primary key is long, the secondary indexes use more space, so it is advantageous to have a short primary key.
若是主鍵過長,二級索引就須要更大的空間,所以,使用短的主鍵列是頗有利的。排序

相關文章
相關標籤/搜索