#建立表格 CREATE TABLE `staffs` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名', `age` int(11) NOT NULL DEFAULT '0' COMMENT '年齡', `pos` varchar(20) NOT NULL DEFAULT '' COMMENT '職位', `add_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入職時間', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='員工記錄表'; #插入數據 insert into `staffs` (`name`, `age`, `pos`, `add_time`) values('z3','22','manager',NOW()); insert into `staffs` (`name`, `age`, `pos`, `add_time`) values('July','23','dev',NOW()); insert into `staffs` (`name`, `age`, `pos`, `add_time`) values('2000','23','dev',NOW()); #查看錶格 select * from staffs; #建立索引,建立表格時,默認只建立主鍵索引,這裏建立複合索引 ALTER TABLE staffs ADD INDEX idx_staffs_nameAgePos(name,age,pos);
全值匹配:當前表格索引有主鍵索引和手動建立的複合索引,當咱們利用複合索引查詢時,若是查詢的字段是索引包含的字段時,WHERE查詢字段的個數小於等於複合索引包含的字段,字段的順序能夠和索引中包含的字段順序不一致。mysql
若是索引了多列,要遵循最左前綴法則。指的是查詢從索引的最左前列開始而且不跳過索引中的列。sql
這裏都複合最佳左前綴法則,創建的索引都用上了。shell
#不遵循索引從最前列開始,致使索引失效,全表掃描 explain select * from staffs where age = 23 and pos = 'dev'; #遵循了縮影從最前列開始,可是跳過了age這個索引,致使pos這個索引失效 explain select * from staffs where name = 'July' and pos = 'dev';
不在索引列上作任何操做(計算、函數、(自動or手動)類型轉換),會致使索引失效而轉向全表掃描。函數
因爲age>11是一個範圍,因此致使pos='manager'這個索引失效。mysql索引
假設建立的複合索引是index(a,b,c)spa
WHERE語句 | 索引是否被使用 |
---|---|
where a = 3 | Y,使用到a |
where a = 3 and b =5 | Y,使用到a,b |
where a = 3 and b = 5 and c = 4 | Y,使用到a,b,c |
where b = 3 或者 where b = 3 and c = 4 或者 where c = 4 | N |
where a = 3 and c = 5 | 使用到a, 可是c不能夠,b中間斷了 |
where a = 3 and b > 4 and c = 5 | 使用到a和b, c不能用在範圍以後,b斷了 |
where a is null and b is not null | is null 支持索引 可是is not null 不支持,因此 a 可使用索引,可是 b不可使用 |
where a <> 3 | 不能使用索引 |
where abs(a) =3 | 不能使用索引 |
where a = 3 and b like 'kk%' and c = 4 | Y,使用到a,b,c |
where a = 3 and b like '%kk' and c = 4 | Y,只用到a |
where a = 3 and b like '%kk%' and c = 4 | Y,只用到a |
where a = 3 and b like 'k%kk%' and c = 4 | Y,使用到a,b,c |