第27课 索引

什么是索引

相当于书籍的目录, 加快查询速度

是不是索引越多越好?

索引会加快查询速度, 但是会拖慢写入速度, 因为每写入一条数据, 都需要重建索引

索引什么时候有用

条件越明确, 索引越有用
通俗点说, 经常where哪个字段, 就给哪个字段加索引

image.png

试验一下

我们为了看出速度上的差别, 我们需要3,000,000行数据...
使用存储过程进行插入

drop table if exists test;

create table test(
    id int,
    name varchar(20),
    sex char(1) default '男',
    age int not null
);

drop procedure if exists batch_insert;

create procedure batch_insert() begin 
    declare i int default 0;
    declare sex_str char(1) default '';
    declare age_int int default 0;
    declare name_str varchar(20) default '';


    while i< 3000000 do
        set i = i + 1;
        set name_str = CONCAT('张三_',i);
        if age_int > 110 then 
            set age_int = 1;
        end if;
        set age_int = age_int + 1;
        if i%3 = 0 then 
            set sex_str = '女';
        else 
            set sex_str = '男';
        end if;

        insert into test(id,sex,age,name) values(i,sex_str,age_int,name_str);
        if i % 100000 = 0 then 
            select CONCAT('当前是第',i,'行...');
        end if;
    end while;
end;

call batch_insert();

耗时比较

image.png

mysql支持多种索引

mysql索引.png

创建索引

建表时创建

drop table if exists test2;
create table test2( 
    id int not null,
    name varchar(20) not null,
    sex tinyint(1) not null,
    age tinyint(1) not null,
    index(id),
    index(name),
    index(sex),
    index(age)
);

desc test2;
image.png
image.png

建表后创建

create index 索引名称 on 表名(字段名)
image.png

查看索引

show index from 表名;
image.png

删除索引

drop index 索引名称 on 表名;
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 转 # https://www.cnblogs.com/easypass/archive/2010/12/ 08/...
    吕品㗊阅读 9,831评论 0 44
  • --- layout: post title: "如果有人问你关系型数据库的原理,叫他看这篇文章(转)" date...
    蓝坠星阅读 833评论 0 3
  • 今天看到一位朋友写的mysql笔记总结,觉得写的很详细很用心,这里转载一下,供大家参考下,也希望大家能关注他原文地...
    信仰与初衷阅读 4,763评论 0 30
  • 索引的基本原理,以及数据是如何被访问的 (一)SQLS如何访问没有建立索引的数据表 Heap译成汉语叫做“堆”,其...
    安易学车阅读 3,503评论 0 8
  • 索引是应用程序设计和开发的一个重要方面。 若索引太多, 应用程序的性能可能会受到影响。 而索引太少, 对查询性能又...
    好好学习Sun阅读 1,059评论 0 4