第27課 索引

什么是索引

相當(dāng)于書籍的目錄, 加快查詢速度

是不是索引越多越好?

索引會加快查詢速度, 但是會拖慢寫入速度, 因為每寫入一條數(shù)據(jù), 都需要重建索引

索引什么時候有用

條件越明確, 索引越有用
通俗點(diǎn)說, 經(jīng)常where哪個字段, 就給哪個字段加索引

image.png

試驗一下

我們?yōu)榱丝闯鏊俣壬系牟顒e, 我們需要3,000,000行數(shù)據(jù)...
使用存儲過程進(jìn)行插入

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('當(dāng)前是第',i,'行...');
        end if;
    end while;
end;

call batch_insert();

耗時比較

image.png

mysql支持多種索引

mysql索引.png

創(chuàng)建索引

建表時創(chuàng)建

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

建表后創(chuàng)建

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

查看索引

show index from 表名;
image.png

刪除索引

drop index 索引名稱 on 表名;
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容