MySQL索引

索引

MySQL官方对索引的定义为:索引(Index)是帮助MySQL高效获取数据的数据结构。

提取句子主干,就可以得到索引的本质:索引是数据结构

1.1、索引的分类

在一个表中,主键索引只能有一个,唯一索引可以有多个

  • 主键索引(primary key)
    • 唯一的标识,主键不可重复,只能有一个主键,多个列可做一个主键
  • 唯一索引(unique key)
    • 避免重复的列出现,唯一索引可以重复,多个列都可以标识为 唯一索引
  • 常规索引(key/index)
    • 默认的,index/key关键字来设置
  • 全文索引(fulltext)
    • 在特定的数据库引擎下才有,MyISAM
    • 快速定位数据
-- 索引的使用
-- 1、在创建表的时候给字段增加索引
-- 2、创建完毕后,增加索引

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

-- 增加一个索引 自取索引名(列名)
alter table `student` add fulltext index 学生名(`studentname`);

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

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

1.2、测试索引

-- 插入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('用户1',i),'13456@qq.com',
		concat('18',floor(rand()*999999999)),
		floor(rand()*2),uuid(),floor(rand()*100));
		set i = i+1;
	end while;
	return i;
end;

select mock_data();

set global log_bin_trust_function_creators = 1; -- 信任子程序的创建者,禁止创建、修改子程序时对SUPER权限的要求,设置log_bin_trust_routine_creators全局系统变量为1。

explain select * from app_user where `name` = '用户1865456'; -- 查看搜索过程
select * from app_user;

-- id_表名_字段名
-- create index 索引名 on 表(字段)
create index id_app_user_name on app_user(`name`);
select * from app_user where `name` = '用户1865456';

索引在小数据量的时候,用户不大,但是在大数据的时候,区别十分明显

1.3、索引原则

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

索引的数据结构

Hash类型的索引
BTree:Innodb的默认数据结构

posted @   习梦生  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示