mysql之索引方面的知識點總結

來源:互聯網
上載者:User

標籤:style   ar   使用   sp   strong   on   資料   bs   ad   

索引的類型:

普通索引:這是最基本的索引類型,沒唯一性之類的限制。

唯一性索引:和普通索引基本相同,但所有的索引列只能出現一次,保持唯一性。

主鍵:主鍵是一種唯一索引,但必須指定為"PRIMARY KEY"。

全文索引:全文索引的索引類型為FULLTEXT。全文索引可以在VARCHAR或者TEXT類型的列上建立。

索引的操作

使用ALTER TABLE語句建立索引。

alter table table_name add index index_name (column_list) ;

alter table table_name add unique (column_list) ;

alter table table_name add primary key (column_list) ;

使用CREATE INDEX語句對錶增加索引。

create index index_name on table_name (column_list) ;

create unique index index_name on table_name (column_list) ;

刪除索引

drop index index_name on table_name ;

alter table table_name drop index index_name ;

alter table table_name drop primary key ;

查看索引

show index from table_name;

如何使用索引

1、在經常進行串連的欄位,建立索引

2、在排序或分組的列上建立索引

3、在條件運算式中建立所因(where),情況有兩種

  不同值較多的列上使用索引,

  不同值較少的列上不適用索引

4、待排序的列有多個,可以在這些列上建立複合索引

5、可以建立短索引,例如:

   alter table table_name add index index_name(column_list(length))

   alter table test add index ab(`a`(3));

6、join中出現的列需要建立索引

注意事項:

1、索引不會包含有null值的列

2、MySQL查詢只使用一個索引,因此如果where子句中已經使用了索引的話,那麼order by中的列是不會使用索引的。因此資料 

庫預設排序可以符合要求的情況下不要使用排序操作;盡量不要包含多列的排序,如果需要最好給這些列建立複合索引。

3、不要在列上進行運算

4、以萬用字元%和_開頭作查詢時,mysql不會使用索引。例如:

會使用索引:SELECT * FROM mytable WHERE username like ‘admin%‘

不會使用索引:SELECT * FROM mytable WHERE username like ‘%admin‘

複合式索引

複合式索引的最左優先原則,複合式索引的第一個欄位必須出現在查詢組句中,這個索引才會被用到。

如果有一個複合式索引(col_a,col_b,col_c)

下面的情況都會用到這個索引:

col_a = "some value";

col_a = "some value" and col_b = "some value";

col_a = "some value" and col_b = "some value" and col_c = "some value";

col_b = "some value" and col_a = "some value" and col_c = "some value";

對於最後一條語句,mysql會自動最佳化成第三條的樣子~~。

下面的情況就不會用到索引:

col_b = "aaaaaa";

col_b = "aaaa" and col_c = "cccccc";

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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.