1. 程式人生 > >MySQL裡的Key和Index有什麼不同?

MySQL裡的Key和Index有什麼不同?

KEY

key 是資料庫的物理結構,它包含兩層意義,一是約束(偏重於約束和規範資料庫的結構完整性),二是索引(輔助查詢用的)。包括primary key, unique key, foreign key 等。

  • primary key 
    有兩個作用,一是約束作用(constraint),用來規範一個儲存主鍵和唯一性,但同時也在此key上建立了一個index;
  • unique key 也有兩個作用,一是約束作用(constraint),規範資料的唯一性,但同時也在這個key上建立了一個index;
  • foreign key也有兩個作用,一是約束作用(constraint),規範資料的引用完整性,但同時也在這個key上建立了一個index;

MySQL中的key是同時具有constraint和index的意義。

<code class="hljs applescript has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">MySQL requires <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">every</span> Key also be indexed, <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">that</span>'s an implementation detail specific <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">to</span> MySQL <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">to</span> improve performance.</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li></ul><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li></ul>

INDEX

index是資料庫的物理結構,它只是輔助查詢的,它建立時會在另外的表空間(mysql中的innodb表空間)以一個類似目錄的結構儲存。索引要分類的話,分為字首索引、全文字索引等;因此,索引只是索引,它不會去約束索引的欄位的行為。 
例如:create table t(id int, index inx_tx_id (id));

總結

我們說索引分類,分為主鍵索引、唯一索引、普通索引(這才是純粹的index)等,也是基於是不是把index看作了key。比如 create table t(id int, unique index inx_tx_id (id)); 這裡的index相當於key的效果。