(11)索引

索引的作用:就是用来加速查找的

索引的缺点:添加或删除数据的时候,效率是很低的

PS:表内不能没有索引,也不能素有列都加上索引,做表的时候要衡量

索引的类型:

1、hash

在使用memory引擎的时候默认的

2、btree

Innodb、MyISAM 引擎下默认的

索引的种类

1、主键索引(唯一索引)

给ID设一个主键索引,并且主键不能为空,自增的

2、唯一索引

列的值不能重复,列的值可以为空

create table in1(
  nid int not null auto_increment primary key,
  name varchar(32) not null,
  email varchar(64) not null,
  extra text,
  unique index_name (name)  #这里就是创建唯一索引
)

3、普通索引

普通索引的添加

create table user(

  id int unsigned auto_increment primary key,

  name char(32) not null default'',

  money int not null default 0,

  index xxx ('列名')  #这里加的就是普通索引

)charset=utf8;

PS: 在查找 select * from 表名 where 列名 = 'xxxx',这时候速度是非常快的

4、联合索引  #建议使用联合索引

使用场景:频繁的同时使用n列来进行查询,如:where n1 = ‘alex’ and n2 = 666

create table user(

  id int unsigned auto_increment primary key,

  name char(32) not null default'',

  money int not null default 0,

  index index_name ('列名',‘’列名‘’)  #这里加的就是联合索引

)charset=utf8;

PS:联合索引效率大于普通索引

关于索引的指令:

1、unique index_name (name)  #建表时候创建唯一索引

2、index xxx ('列名')  #建表时候创建普通索引

3、index index_name ('列名',‘’列名‘’)  #建表时候创建联合索引

4、create index index_name on table_name(column_name)  #表已经建立后在创建普通索引

5、drop index_name on table_name;  #删除普通索引索引

6、show index from table_name;  #查看普通索引索引

7、create unique index 索引名 on 表名(列名)  #表已经建立后创建唯一索引

8、drop unique index 索引名 on 表名  #删除唯一所以

9、create index ix_name_email on in3(name,email); #表已经建立后在创建联合索引

正确的使用索引

数据库表中添加索引后确实会让查询速度起飞,但前提必须是正确的使用索引来查询,如果以错误的方式使用,则即使建立索引也会不奏效。
即使建立索引,索引也不会生效:

- like '%xx'
select * from tb1 where name like '%cn';
 
- 使用函数
select * from tb1 where reverse(name) = 'xxx';
 
- 类型不一致
如果列是字符串类型,传入条件是必须用引号引起来,不然...
select * from tb1 where name = 999;
 
- order by
select email from tb1 order by name desc;
当根据索引排序时候,选择的映射如果不是索引,则不走索引
特别的:如果对主键排序,则还是走索引:
select * from tb1 order by nid desc;
 
- 组合索引最左前缀
如果组合索引为:(name,email)
name and email -- 使用索引
name -- 使用索引
email -- 不使用索引
PS:就算name和email都添加了索引,但是在索引时候不是从左边开始的,也是无法调用索引的,所以索引的规则就是必须从左边顺序开始
 
- 避免使用select *
- 在使用函数count(1)或count(列)的时候,不要用count(*),括号里最好指定值
- 创建表时尽量时 char 代替 varchar
- 表的字段顺序固定长度的字段优先
- 组合索引代替多个单列索引(经常使用多个条件查询时)
- 使用连接(JOIN)来代替子查询(Sub-Queries)
- 索引散列值(重复少的值)不适合建索引,例:性别不适合
 
 
explain + 查询SQL - 用于显示SQL执行信息参数,根据参考信息可以进行SQL优化
分析语句是否能用索引  #语句后面加G就会以下面的形式陈列
PS:type是ALL代表全表扫描,possible_keys就是如果有索引,下面就会显示这条语句可能会执行的索引类型, key_len代表真实使用索引的长度,key代表真实使用到的索引,rows就是行数
 
type的类型
ALL 全表扫描,对于数据表从头到尾找一遍
select * from tb1;
特别的:如果有limit限制,则找到之后就不在继续向下扫描
select * from tb1 where email = 'xxxx@live.com'
select * from tb1 where email = 'xxxx@live.com' limit 1;
虽然上述两个语句都会进行全表扫描,第二句使用了limit,则找到一个后就不再继续扫描。
 
INDEX 全索引扫描,对索引从头到尾找一遍
select nid from tb1;
 
RANGE 对索引列进行范围查找
select * from tb1 where name < 'xxx';
 
REF 根据索引查找一个或多个值
select * from tb1 where name = 'xxx';
 
CONST 常量
表最多有一个匹配行,因为仅有一行,在这行的列值可被优化器剩余部分认为是常数,const表很快,因为它们只读取一次。
select nid from tb1 where nid = 2 ;
 
SYSTEM 系统
表仅有一行(=系统表)。这是const联接类型的一个特例。
原文地址:https://www.cnblogs.com/shizhengquan/p/10315259.html