mysql-explain

来源:互联网 发布:儿童编程教育市场 编辑:程序博客网 时间:2024/05/16 14:02

假设新建一张表,

如下:

CREATE TABLE `td_emplyee` (`id` int(11) NOT NULL DEFAULT '1000',`employee_name` varchar(256) DEFAULT NULL COMMENT '员工姓名',`age` int(11) DEFAULT NULL COMMENT '年龄',`sex` varchar(2) DEFAULT NULL COMMENT '性别',`department` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='员工表';

插入几条数据,主键依次是1000到1006

目前只有一个主键索引,也是聚簇索引。

explain的列的含义请移步到(参考http://blog.csdn.net/woshiqjs/article/details/24135495)。

1.执行 explain select * from td_emplyee 

id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra  

'1', 'SIMPLE', 'td_emplyee','ALL', NULL, NULL, NULL, NULL,'2', NULL


2.执行explain select * from td_emplyee where id > 1000

id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra  

'1', 'SIMPLE', 'td_emplyee','range','PRIMARY', 'PRIMARY','4', NULL, '6', 'Using where'

3. 执行explain select id from td_emplyee where id > 1000

id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra

'1','SIMPLE','td_emplyee','range','PRIMARY','PRIMARY','4',NULL,'6','Using where; Using index'

注意,Extra中有Using index,这就是覆盖索引,这个查询很快,因为无需回表查询。

4.执行explain select id from td_emplyee order by id

id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra

'1', 'SIMPLE', 'td_emplyee','index',NULL, 'PRIMARY','4' , NULL,'7', 'Using index'
 此时,type为index,表示使用了索引扫描来排序。
5.执行explain select id,employee_name from td_emplyee order by id desc 
id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra
'1', 'SIMPLE', 'td_emplyee','index',NULL, 'PRIMARY','4', NULL,'7', NULL

注意,该条执行计划和上面第4个的区别是,Extra为null,而第4个是Using index(覆盖索引),另外,虽然type都是index,表示使用索引扫描来排序,但是这种排序效率很低,特别是I/O密集型的情况下,因为每次扫描一个索引,都要发生一次回表查询(多一次I/O)。

6.执行explain select id,employee_name from td_emplyee where employee_name = 'ss' order by id desc 

id, select_type, table, type, possible_keys, key, ken_len, ref, rows, Extra
'1', 'SIMPLE', 'td_emplyee','index',NULL, 'PRIMARY','4', NULL,'7', 'Using where'

  下面,对employee_name列见索引,即二级索引

ALTER TABLE `test`.`td_emplyee` 
ADD INDEX `employee_name_index` USING BTREE (`employee_name` ASC)  KEY_BLOCK_SIZE=10 COMMENT '';

  执行时,会报错,错误信息如下:

ERROR 1071: Specified key was too long; max key length is 767 bytes

调整key length

ALTER TABLE `test`.`td_emplyee` 
ADD INDEX `employee_name_index` USING BTREE (`employee_name(64) ` ASC)  KEY_BLOCK_SIZE=10 COMMENT '';

如果想深入了解,移步http://dev.mysql.com/doc/refman/5.5/en/explain-output.html#explain-join-types





0 0