MySQL---索引

來源:互聯網
上載者:User

標籤:--   incr   color   arc   column   round   font   有一個   技術   

索引,是資料庫中專門用於協助使用者快速查詢資料的一種資料結構。類似於字典中的目錄,尋找字典內容時可以根據目錄尋找到資料的存放位置,然後直接擷取即可。

以 B-tree 形式儲存:

1                     302  3         10                        404  5    5         15            35             666  7 1   6     11    19      21      39     55     100

MySQL中常見索引有:

  • 普通索引
  • 唯一索引
  • 主鍵索引
  • 複合式索引

1、普通索引

普通索引僅有一個功能:加速查詢

1 create table in1(2     nid int not null auto_increment primary key,3     name varchar(32) not null,4     email varchar(64) not null,5     extra text,6     index ix_name (name)7 )
建立表 + 索引
1 create index index_name on table_name(column_name)
建立索引
1 drop index_name on table_name;
刪除索引
1 show index from table_name;
查看索引

注意:對於建立索引時如果是BLOB 和 TEXT 類型,必須指定length。

1 create index ix_extra on in1(extra(32));
View Code

2、唯一索引

唯一索引有兩個功能:加速查詢 和 唯一約束(可含null)

1 create table in1(2     nid int not null auto_increment primary key,3     name varchar(32) not null,4     email varchar(64) not null,5     extra text,6     unique ix_name (name)7 )
建立表 + 唯一索引
1 create unique index 索引名 on 表名(列名);
建立唯一索引
1 drop unique index 索引名 on 表名;
刪除唯一索引

3、主鍵索引

主鍵有兩個功能:加速查詢 和 唯一約束(不可含null)

 1 create table in1( 2     nid int not null auto_increment primary key, 3     name varchar(32) not null, 4     email varchar(64) not null, 5     extra text, 6     index ix_name (name) 7 ) 8  9 OR10 11 create table in1(12     nid int not null auto_increment,13     name varchar(32) not null,14     email varchar(64) not null,15     extra text,16     primary key(ni1),17     index ix_name (name)18 )
建立表 + 建立主鍵
1 alter table 表名 add primary key(列名);
建立主鍵
1 alter table 表名 drop primary key;2 alter table 表名  modify  列名 int, drop primary key;
刪除主鍵

4、複合式索引

複合式索引是將n個列組合成一個索引

其應用情境為:頻繁的同時使用n列來進行查詢,如:where n1 = ‘alex‘ and n2 = 666。

1 create table in3(2     nid int not null auto_increment primary key,3     name varchar(32) not null,4     email varchar(64) not null,5     extra text6 )
建立表
1 create index ix_name_email on in3(name,email);
建立複合式索引

如上建立複合式索引之後,查詢(最左首碼):

  • name and email  -- 使用索引
  • name                 -- 使用索引
  • email                 -- 不使用索引

注意:對於同時搜尋n個條件時,複合式索引的效能好於多個單一索引合并。

補充

1、覆蓋索引

select * from tb where nid=1;# 先去索引中找# 再去資料中找select nid from tb where nid<10;# 先去索引中找(只需要在索引表中就能擷取到資料)# 該情況應用上索引,並且不用去資料表中操作,即覆蓋索引。

2、合并索引(根據業務需求決定)

 

MySQL---索引

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.