查看sql语句的执行计划:
explain select ename,sal from emp where ename='SMITH';
给薪资sal字段添加索引
create index emp_sal_index on emp(sal);
查看sql语句的执行计划:
explain select ename,sal from emp where ename='SMITH';
mysql>explainselect ename,sal from emp where ename='smith';+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+| id | select_type |table| partitions |type| possible_keys |key| key_len | ref |rows| filtered | Extra |+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+|1|SIMPLE| emp |NULL|ALL|NULL|NULL|NULL|NULL|14|10.00|Usingwhere|+----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------------+1rowinset,1 warning (0.01 sec)
mysql>createindex emp_sal_index on emp(sal);
Query OK,0rows affected (0.05 sec)
Records: 0 Duplicates: 0Warnings: 0
mysql>explainselect ename,sal from emp where sal='800';+----+-------------+-------+------------+------+---------------+---------------+---------+-------+------+----------+-----------------------+| id | select_type |table| partitions |type| possible_keys |key| key_len | ref |rows| filtered | Extra |+----+-------------+-------+------------+------+---------------+---------------+---------+-------+------+----------+-----------------------+|1|SIMPLE| emp |NULL| ref | emp_sal_index | emp_sal_index |5| const |1|100.00|Usingindex condition |+----+-------------+-------+------------+------+---------------+---------------+---------+-------+------+----------+-----------------------+1rowinset,1 warning (0.01 sec)
4.6 索引底层采用的数据结构是:B+Tree
4.7 索引的实现原理:
通过BTree缩小扫描范围。底层索引进行了排序,分区,索引会携带数据在表中的‘物理地址’
最终通过索引检索到数据之后,获取到关联的物理地址,通过物理地址定位表中的数据,效率最高
select ename from emp where ename='SMITH';
通过索引转换为:
select ename from emp where 物理地址=0x3;