mysql数据库索引的优化,实践,实操

    技术2022-07-11  82

    实验一个有43万数据的表,索引情况:对uid设置了UNIQUE(约束唯一标识数据库表中的每条记录)唯一索引;对mobile设置了NORMAL(普通索引)。

    1、查看数量

    select count(*) from user;查询时间:34s(索引失效)

    select count(uid) from user;查询时间:4.238s(索引失效)

    select count(uid) from user where uid is not null;查询时间:0.190s(索引生效)

    这里的原因是字段有null的情况,就会全表查询,然而加上“is not null”就会使索引生效,在字段没有null的情况索引生效。

     

    2、查看某一条数据

    select * from user where uid = 99999;查询时间:0.165s(索引有效)

    当在增加了函数和条件后,查询还是有索引加持,如下:

    select max(length('nickname')) as max_name from user;查询时间:0.173s(索引有效)

     

    3、已where条件的函数来实践哪些添加会导致索引失效

    (1)like 在条件前面加上%就会导致索引失效  select * from user where mobile like '%';查询时间:0.769s(索引失效)

    但是只要前面不加“%”,索引就能生效select * from user where mobile like '13%';查询时间:0.769s(索引生效)

    (2)or 若条件其中有不是索引的字段,就会失效  select uid from user where uid = 9999 or headimgurl = "80fvbT";(索引失效)查询时间:0.560s

    但是or的条件都是索引的字段,就是索引生效的 select uid from user where uid = 9999 or uid =99999;(索引生效)查询时间:0.130s

    (3)字段的类型是char或者varchar等string类型的,索引生效的是要将内容增加双引号的,原因是原来字段的类型是char,若写了内容是int型,就会做隐式转换,导致索引失效。

    select * from user where mobile = 13;查询时间:1.066s(索引失效)

    select * from user where mobile = "13";查询时间:0.169s(索引生效)

     

    Processed: 0.015, SQL: 9