您当前的位置: 首页 >  sql

网易测试开发猿

暂无认证

  • 2浏览

    0关注

    221博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

MySQL索引(详解)

网易测试开发猿 发布时间:2021-11-18 19:50:29 ,浏览量:2

MySQL索引(详解)

一、理解索引   首先:先假设有一张表,表的数据有20W条数据,其中有一条数据是name = ‘newdream’,如果要拿这条数据的话需要些的 sql 是:select * from stu where name= ‘newdream’

  一般情况下,在没有建立索引的时候,MySQL需要扫描全表及扫描20W条数据找这条数据,如果在name字段上建立索引,那么mysql只需要扫描一行数据及为我们找到这条name = 'newdream’的数据,这样的情况下查询的速度会要提高很多

  索引的设计往往需要一定的技巧,掌握了这些技巧,可以确保索引能够大幅地提升数据检索效率,弥补索引在数据更新方面带来的缺陷。

原则1:表的某个字段值离散度越高,该字段越适合选作索引的关键字

原则2:占用储存空间少的字段更适合选作索引的关键字

原则3:较频繁地作为where查询条件的字段应该创建索引,分组字段或者排序字段应该创建索引,两个表的连接字段应该创建索引

原则4:更新频繁的字段不适合创建索引,不会出现在where子句中的字段不应该创建索引

原则5:最左前缀原则

原则6:尽量使用前缀索引

索引的种类:      主索引、聚簇索引      唯一性索引      普通索引      复合索引      全文索引(fulltext)

  二、创建索引 方法一:创建表的同时创建索引

create table 表名(	
字段名1 数据类型 [约束条件],	
...	
[其他约束条件],	
...
[unique | fulltext ] index [索引名] (字段名[(长度)] [asc | desc ])	
)engine=存储引擎类型 default	charset=字符集类型;

例如:

create table book(
	isbn char(20) primary key,	
	name char(100) not	null,	
	brief_introduction text not null,
	price decimal(6,2), 
	publish_time date not null,	
	unique index isbn_unique (isbn), 
	index name_index (name(20)),	
	fulltext index brief_fulltext (name,brief_introduction),	
	index complex_index(price,publish_time)
)engine=MyISAM default charset=gbk;

方法二:在已有表上创建索引 语法格式①:

create [unique | fulltext] index 索引名 on 表名 (字段名[(长度)] [asc | desc]);

语法格式②:

alter table 表名 add [unique | fulltext] index 索引名 (字段名 [(长度)] [asc | desc]);

三、使用索引的语法 如:

select studentid,score from score use index(index_stuid) where studentid>=3;

四、删除索引的语法 如:

drop index 索引名 on 表名;
关注
打赏
1665054478
查看更多评论
立即登录/注册

微信扫码登录

0.0439s