[MySQL光速入门]027 索引

什么是索引

至关于书籍的目录, 加快查询速度mysql

是否是索引越多越好?

索引会加快查询速度, 可是会拖慢写入速度, 由于每写入一条数据, 都须要重建索引sql

索引何时有用

条件越明确, 索引越有用post

通俗点说, 常常where哪一个字段, 就给哪一个字段加索引mysql索引

image.png

试验一下

咱们为了看出速度上的差异, 咱们须要3,000,000行数据... 使用存储过程进行插入ui

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

快速跳转

相关文章
相关标签/搜索