1. 程式人生 > 其它 >《MySQL資料庫》索引詳解

《MySQL資料庫》索引詳解

前言

索引在資料庫中至關重要,必須要牢牢掌握,在看索引篇之前必須掌握InnoDB 的資料結構:https://www.cnblogs.com/jssj/p/devil_osiris.html

索引建立與刪除

主鍵索引建立:

mysql> alter table ic_user add primary key(id);

主鍵索引刪除:

mysql> alter table ic_user drop primary key;

唯一索引建立:

mysql> alter table ic_user add unique (name);

唯一索引刪除:

mysql> alter table ic_user drop index name;

普通索引建立:

mysql> alter table ic_user add index index_name(name);

普通索引刪除:

mysql> alter table ic_user drop index index_name;

字首索引建立:

mysql>alter table t add key(password(7));

字首索引刪除:

mysql>alter table t drop index password;

建立索引規範

(1) 必須要有主鍵,如果沒有可以做為主鍵條件的列,建立無關列

(2) 經常做為where條件列 order by group by join on, distinct 的條件(業務:產品功能+使用者行為)

(3) 最好使用唯一值多的列作為索引,如果索引列重複值較多,可以考慮使用聯合索引

(4) 列值長度較長的索引列,我們建議使用字首索引.

(5) 降低索引條目,一方面不要建立沒用索引,不常使用的索引清理,percona toolkit(xxxxx)

(6) 索引維護要避開業務繁忙期

其他

select * from sys.schema_unused_indexes; -- 查詢不常被使用的索引

總結

This moment will nap, you will have a dream; But this moment study,you will interpret a dream.