MySQL索引小白必备入门篇

索引分几类:

按照索引的存储来划分:
聚簇索引:innodb,数据文件和索引文件放在同一文件中,因此要指定一个key值(此处key值不是主键,而是索引);关于key值翻译过来是主键的争议:其实key值翻译成主键是不太对的,因为我们建表时不一定有主键,这时innodb会从其他列中选择一个唯一键来创建聚簇索引,如果连唯一键也没有,就会选择6字节的rowid(用户不可见)来创建聚簇索引数据要跟某个索引关联在一起才能查找
非聚簇索引:myisam,数据文件和索引文件不放在同一文件中

按照使用来分:
主键索引:建表时设置主键
唯一索引:建表时设置唯一键
mysql默认创建主键索引和唯一索引:
create table test(id int primary key,name varchar(10) unique);

普通索引(辅助):回表:通过普通索引去树中查找返回主键值,根据主键去索引树查找数据,建立普通索引,Mysql会再为这个索引创建一颗B+树,叶节点包含的不再是数据,而是对应的。
例子:
建表时:id(primary key),name(普通),age,sex,address
使用:select id,age from test where name=‘zhangsan’;
覆盖索引:
例子:
id(primary key),name(普通),age,sex,address
select id,age from test where name=‘zhangsan’;
select id,name from test where name=‘zhangsan’;
组合索引:最左匹配:条件中至少包含索引中最左边字段
例子:
name,age(组合索引)
select * from test where name=?and age=?;
select * from test where name=?;
select * from test where age=?;
select * from test where age=? and name=?;(这个虽然顺序调了,但在mysql的组织架构中的server层的优化器会把age=? and name=?顺序调换回来)
除了3都符合
全文索引:本质和常用的模糊匹配使用 like + % 相同。
建索引语法:
select * from fulltext_test
where match(content,tag) against(‘xxx xxx’);
例子:
建表:
create table Test (
id int ,
content text not null,
primary key(id),
fulltext key content_index(content)
) engine=MyISAM default charset=utf8;
插数据:
insert into Test (content) values (‘x’),(‘l’),(‘h’);
insert into Test (content) values (‘xx’),(‘ll’),(‘hh’);
insert into Test (content) values (‘xxx’),(‘lll’),(‘hhh’);
insert into Test (content) values (‘xxxx’),(‘llll’),(‘hhhh’);
测试:
select * from Test where match(content) against(‘x’);
只有一条结果
只有执行select * from Test where match(content) against(‘xxxx’);才会搜到xxxx这一条,原因如下:在MySQL 的全文索引中,有最小搜索长度和最大搜索长度两个变量,对于长度小于最小搜索长度和大于最大搜索长度的词语,都不会被索引。也就是说,只有这个词语的长度在以上两个变量的区间内,才能对一个词语使用全文索引搜索
MySQL索引小白必备入门篇_第1张图片

你可能感兴趣的:(笔记)