mysql

mysql索引小结

2019-02-26  本文已影响0人  ysp123

1.搭建mysql测试环境

create table s1(
    id int,
    name varchar(20),
    gender char(6),
    email varchar(50)
);

模拟三百万数据入库

delimiter $$

create procedure auto_insert1()
  BEGIN
      declare i int default 1;
      while(i<3000000)do
          insert into s1 values(i,concat('egon',i),'male',concat('egon',i,'@oldboy'));
          set i=i+1;
      end while;
  END$$

delimiter ;

show create procedure auto_insert1\G ;

call auto_insert1();

mysql所以简单操作:测试s1表添加主键

    alter table s1 add primary key(id)

添加主键前后执行:

  select count(*)  from s1;

添加单列索引:

列:alter table s1 add index email (email);

通过使用explain sql语句可以看到使用了索引:


添加组合索引:

alter table tablename add index indexname(column1, column2);

组合索引sql使用遵循最左原则:按照所以从左到右的顺序匹配(备注:索引字段的顺序可以任意调整)。
尽量选择区分度较高的字段创建索引。

添加索引:
alter table s1 add index name_email (name, email);

遵循最左原则执行sql:



sql违反最左原则,则不使用索引:


组合索引使用order by尽量使用index方式排序,避免使用filesort方式排序。
组合索引使用order by排序,排序字段应包含在select字段中,否则索引不使用。




组合索引中order by多字段排序,排序方式应保持一致,否则不使用索引。



组合索引order by排序遵循最左原则
上一篇 下一篇

猜你喜欢

热点阅读