mySQL之索引

来源:互联网 发布:淘宝怎么做手机上 编辑:程序博客网 时间:2024/06/15 18:55

作用

为了加快查询速度,创建了索引~

btree

树形结构,索引的创建基于此进行数据索引创建,层级越少I/O越少,查询效率越高。

创建删除索引的方式

create index 索引名 on 表名(字段名);
drop index 索引名 on 表名;

索引覆盖

  1. 所有查询操作和索引有关,查询效率最高
  2. 索引字段要尽量的小
  3. 索引的最左匹配特性:索引都是从最左开始匹配

考虑到一次I/O操作代价较高,操作系统做了一些优化,查询数据发生I/O时,操作系统会将要查询的磁盘地址数据和左右相邻的数据都加载到内存~

创建索引时注意

  1. 要将索引加到条件的字段
  2. 数据量大时创建索引时慢并且占内存空间,查询时很快,增删改很慢
  3. innodb的索引表会存放于.ibd文件中,myisam的索引存放于.MYI表中

mysql> select * from s1 where id>3 and name=’egon’ and email=’alex333@oldboy.com’ and gender=’male’;
Empty set (0.39 sec)

mysql> create index idx on s1(id,name,email,gender); #未遵循最左前缀
Query OK, 0 rows affected (15.27 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> select * from s1 where id>3 and name=’egon’ and email=’alex333@oldboy.com’ and gender=’male’;
Empty set (0.43 sec)

mysql> drop index idx on s1;
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> create index idx on s1(name,email,gender,id); #遵循最左前缀
Query OK, 0 rows affected (15.97 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> select * from s1 where id>3 and name=’egon’ and email=’alex333@oldboy.com’ and gender=’male’;
Empty set (0.03 sec)

最左前缀匹配:要有最左面的字段做前缀索引才能生效!!!
索引组合:有or并且条件的字段都是索引
索引合并:有and并且条件的字段是组合索引

原创粉丝点击