索引

索引

1. 索引的分类

MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。提取句子主干,就可以得到索引的本质:索引是数据结构。

1. 主键索引(primary key)

唯一的标识,主键不可重复,只能有一个列作为主键

2. 唯一索引(unique key)

避免重复的列出现,唯一索引可以重复,多个列都可以标识为唯一索引

3. 常规索引(key / index)

默认的,index或者key关键字来设置

4. 全文索引(fulltext)

在特定的数据库引擎下才有,MYISAM

快速定位数据

2. 索引的使用

1. 基础语法

-- 索引的使用
-- 方法一:在创建表的时候给字段增加索引
-- 方法二:创建完毕后,增加索引

-- 显示所有的索引信息
show index from student

-- 增加一个全文索引	(索引名) 列名
alter table `student` add fulltext index `studentname`(`studentname`)

-- exlpain 分析SQL执行的状况
explain select * from `student` 	-- 非全文索引

explain select * from student where match(studentname) against('赵')

2. 测试索引

create table `app_user` (
`id` bigint(20) unsigned not null auto_increment,
`name` varchar(50) default '',
`email` varchar(50) not null,
`phone` varchar(20) default '',
`gender` tinyint(4) unsigned default '0',
`password` varchar(100) not null default '',
`age` tinyint(4) default null,
`create_time` datetime default current_timestamp,
`update_time` timestamp not null default current_timestamp on update current_timestamp,
primary key (`id`)
) engine=innodb default charset=utf8

-- 插入100万数据
delimiter $$	-- 写函数之前必须要写,标志
create function mock_data()
returns int
begin
  declare num int default 1000000;
  declare i int default 0;
  
  while i < num do
    -- 插入语句
    insert into `app_user` (`name`,`email`,`phone`,`gender`,`password`,`age`) 
    values (concat('用户',i), '748945489@qq.com', concat('18',floor(rand()*100000000)),floor(rand()*2),uuid(),floor(rand()*100));
    set i = i + 1;
  end while;
  return i;
end;
select mock_data();

select * from `app_user` where `name` = '用户9999'

explain select * from `app_user` where `name` = '用户9999'

-- id_表名_字段名,命名规范
-- create index 索引名 on 表(字段)
create index id_app_user_name on `app_user` (`name`);

explain select * from `app_user` where `name` = '用户9999'

索引在小数据量的时候,用处不大

但是在大数据的时候,区别十分明显

3. 索引原则

  • 索引不是越多越好
  • 不要对进程变动数据加索引
  • 小数据量的表不需要加索引
  • 索引一般加在常用来查询的字段上

4. 索引的数据结构

Hash类型的索引

Btree:INNODB的默认数据结构

原文地址:https://www.cnblogs.com/wang-sky/p/13500763.html