標籤:mysql--索引
- | 索引的作用1、約束2、加速尋找- | 為什麼索引可以這麼快?為什麼索引可以這麼快?name列建立索引建立一個檔案,name列所有資料拿出來通過數字來標記,在一種特殊的資料結構中尋找層級越多,越快(B-tree索引)| 索引的種類-| 普通索引-- 加速尋找1-建立表-建立索引--建立表的同時建立索引create table in1( nid int not bull auto_increment primary key, name varchar(32) not null, email varchar(64) not null, index ix_name (name));2-建立索引-- 在建立表之後再去建立索引create index 索引名 on 表名(列名)create index index_name on table_name(column_name)3-刪除索引# errordrop index index_name on table_name;4-查看索引show index from table_name-| 唯一索引-- 加速尋找,約束列資料不能重複,null1-建立表-建立索引-- 建立表的同時建立唯一索引create table in1( nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text, unique ix_name (name));2-建立索引-- 在建立表之後再取建立索引create unique index 索引名 on 表名(列名)3-刪除索引drop unique index 索引名 on 表名-| 主鍵索引-- 加速尋找,約束列資料不能重複,不能null1-建立表-建立索引create table in1( nid int not null auto_increment primary key, name varchar(32) not null, email varchar(64) not null, extra text, index ix_name (name))ORcreate table in1( nid int not null auto_increment, name varchar(32) not bull, email varchar(64) not null, extra text, primary key(nid), index ix_name (name))2-建立主鍵alter table 表名add primary key(列名)3-刪除主鍵alter table 表名 drop primary key;alter table 表名 modify 列名 int, drop primary key;-| 複合式索引-- 多列可以建立一個索引檔案2-聯合唯一索引: 有約束,兩列資料都不相同,才能插入,不然報錯# 尋找:最左匹配(最左首碼)select * from tb1 where name = ‘alex‘select * from tb1 where name = ‘alex‘ and pwd = ‘123‘select * from tb1 where pwd = ‘123‘ # 不會走索引- | 索引的優缺點--增刪改慢,耗費資源--尋找快- | 覆蓋索引-- 下例中nid設定了索引select * from tb where nid=1;# 先去索引中找# 再取資料表中找select nid from tb where nid < 10;-- 情況應用上了索引,並且不用去資料庫中操作,覆蓋索引# 只需要在索引表中就能擷取資料- | 合并索引-- 列: nid, name(單獨索引) ,email(單獨索引), pwd select * from tb where name = ‘alex‘ select * from tb where email = ‘[email protected]‘ select * from tb where name = ‘alex‘ or email = ‘[email protected]‘ # 合并索引- | 執行計畫-- 相對比較準確的表達出當前SQL啟動並執行狀況-- 是否走索引,走的是什麼索引1、 explain SQL語句 type:ALL -- 全資料表掃描 type:index -- 全索引表掃描2、limit select * from tb1 where email = ‘123‘; select * from tb1 where email limit = 1;----- SQL: ALL、Index, 都是有最佳化的餘地 -----3、range 執行範圍查詢,type是range, 如果沒有索引type是ALL,全表掃描注意:!= 和 > 符號,不走索引
MySQL--索引