Mysql索引类型介绍

1.定义
索引(index)是帮助Mysql高效获取数据的数据结构

2.分类

  • 主键索引(Primary key)
    唯一的标识,主键不可重复,一个表中只能有一个列作为主键

  • 唯一索引(Unique key)
    不能重复,一个表中多个列可以标识为唯一索引

  • 常规索引(key/index)
    默认的索引,可以重复,多个列可以标识为常规索引

  • 全文索引(FullText)
    一般为MyIsAmy引擎才支持

3.索引原则

  • 索引不是越多越好:
    不要对经常变动的列增加索引,应该对经常查询的列增加索引,数据量少的表不需要加索引

4.常用操作

show index from `XXX` -- 查看表XXX索引
alter table `XXX` add fulltext index `xxxx` (`xxxx`) --表XXX增加一个全文索引,索引名为`xxxx`,在字段(`xxxx`)中增加:索引名(字段)
alter table `XXX` add unique index `xxxx` (`xxxx`) --表XXX增加一个唯一索引,索引名为`xxxx`,在字段(`xxxx`)中增加:索引名(字段)
alter table `XXX` add index `xxxx` (`xxxx`) --表XXX增加一个常规索引,索引名为`xxxx`,在字段(`xxxx`)中增加:索引名(字段)
drop index `xxxx` on XXX --删除表XXX中的名字为xxxx的索引
explain select * from XXX match(xxxx) against ('x') --查找字段xxxx带有x的数据

5.插入大量数据测试示例

DELIMITER $$ --mysql自定义函数起始标志
CREATE FUNCTION insert_data() --创建一个sql函数,返回值为int
RETURNS INT

BEGIN
	DECLARE NUM INT DEFAULT 50000;
	DECLARE I INT DEFAULT 0;
	
	WHILE I < NUM DO
		insert into test (`name`, `phone_no`, `pass_word` ) values (concat('用户',I), concat('18',floor(rand()*((999999999-100000000)+100000000))),uuid());
		SET I = I+1;
		END WHILE;
		RETURN I;
END;

SELECT insert_data();

没有索引前,执行查询操作:

select * from test where name = '用户999999';

耗时:
image

慢查询分析:

select * from test where name = '用户999999';

image

增加索引后,执行查询操作:

alter table test add unique index `name` (`name`);
select * from test where name = '用户999999';

耗时:
image

慢查询分析:

select * from test where name = '用户999999';

image

posted @ 2023-06-04 11:24  遥遥领先  阅读(42)  评论(0编辑  收藏  举报