explain分析
Extra字段中的'Using files'表示需要排序,mysql给每个线程分配内存用于排序
select city,name,age from t where city='杭州' order by name limit 1000 ;
1、初始化sort_buffer,确定将需要返回的字段放入
2、从索引city中找到满足条件的主键ID
3、到主键ID索引,取要返回的字段,存入sort_buffer中
4、从索引city取下一个记录的主键
5、重复3、4(2不是要判断是否满足条件吗,不用重复吗?)
6、对sort_buffer中的数据按name做快排
7、取前1000行返回
/* 打开 optimizer_trace,只对本线程有效 */
SET optimizer_trace='enabled=on';
/* @a 保存 Innodb_rows_read 的初始值 */
select VARIABLE_VALUE into @a from performance_schema.session_status where variable_name = 'Innodb_rows_read';
/* 执行语句 */
select city, name,age from t where city='杭州' order by name limit 1000;
/* 查看 OPTIMIZER_TRACE 输出 */
SELECT * FROM `information_schema`.`OPTIMIZER_TRACE`\G
/* @b 保存 Innodb_rows_read 的当前值 */
select VARIABLE_VALUE into @b from performance_schema.session_status where variable_name = 'Innodb_rows_read';
/* 计算 Innodb_rows_read 差值 */
select @b-@a;
sort_mode:参与排序的字段
number_of_tmp_files:内存不够,硬盘提供的临时文件数量
全字段排序:将所有需要返回的字段放到sort_buffer里(优先)
rowid排序:将主键和排序字段放到sort_buffer里
联合索引可以避免使用sort_buffer.