索引的類型
主鍵索引
- 創建表的時候指定主鍵
-- 創建表
create table t_user(
id varchar(32) not null,
nickname varchar(20) not null,
age tinyint not null default 0,
gender tinyint not null default 2,
birthday date not null default ‘1997-01-01’,
id_card char(18) not null default '',
remark varchar(512) not null default '',
primary key(id)
);
-- 查看t_user表中的索引
show index in t_user;
- 在創建完表之后指定
-- 創建沒有指定主鍵的表
create table t_demo(id varchar(32) not null, name varchar(20) not null);
-- 設置主鍵
alter table t_demo add primary key(id);
-- 查看
show index in t_demo;
唯一索引
唯一索引的命名一般以uniq
作為前綴,下劃線風格。
alter table t_user add unique uniq_nickname(nickname);
show index in t_user;
普通索引
普通索引的命名一般以idx
作為前綴,下劃線風格。
alter table t_user add index idx_age(age);
組合索引
-- 創建身份證號、出生年月、性別的組合索引
alter table t_user add index idx_idcard_birth_gender(id_card, birthday, gender);
全文索引
MyISam才支持全文索引
alter table t_user add fulltext index idx_remark(remark);
索引未命中場景
- 有隱式轉換
explain select * from t_user where mobile = 15333333333;
mobile
是varchar類型的,但是查詢并沒有帶單引號(''
),會導致索引未命中,正確應該如下:
explain select * from t_user where mobile = '15333333333';
- 有負向查詢
# 主鍵id上的操作
explain select * from t_user where id = 1;
explain select * from t_user where id <> 1;
# 在屬性age上的操作
explain select * from t_user where age = 23;
explain select * from t_user where age != 23;
執行完之后,我們可以發現主鍵id
上的負向查詢用到了索引,不過執行計劃中的type
是range
。
在age上的負向查詢就沒有命中索引。
- 有前導模糊查詢
explain select * from t_user where mobile like '%185';
從執行計劃中我們能看到,索引沒有命中,是全表掃描的。
但是下面這樣的插敘是能命中索引的:
explain select * from t_user where mobile like '185%';
- 查詢條件字段上有計算
explain select * from t_user where age - 1 = 22;
explain select * from t_user where pow(age, 2) = 200;
explain select * from t_user where mobile = concat(mobile, 'm');
上面的是不能命中索引的