我通过我与SugarCRM公司遇到的问题,研究一种特殊的顺序,我认为下面的测试案例描述:排序索引使用
鉴于以下两个表:
CREATE TABLE test1 ( id int(11) NOT NULL AUTO_INCREMENT, name char(20), PRIMARY KEY (id) ); CREATE TABLE test2 ( id int(11) NOT NULL AUTO_INCREMENT, name char(20), name2 varchar(10), PRIMARY KEY (id) );
将随机数据插入表test1:
delimiter $$ create procedure randomizer() begin declare i int Default 0 ; declare random char(20) ; declare random2 char(10) ; myloop: loop set random=conv(floor(rand() * 99999999999999), 20, 36) ; insert into test1 (id, name) VALUES (i+1,random) ; set i=i+1; if i=1000 then leave myloop;
end if; end loop myloop; 结束$$ 定界符;
插入随机数据到表TEST2:
delimiter $$ create procedure randomizer() begin declare i int Default 0 ; declare random char(20) ; declare random2 char(10) ; myloop: loop set random=conv(floor(rand() * 99999999999999), 20, 36) ; set random2=conv(floor(rand() * 999999), 10, 36) ; insert into test2 (id, name, name2) VALUES (i+1,random, random2) ; set i=i+1; if i=1000 then leave myloop;
END IF; end loop myloop; 结束$$ 定界符;
添加二级指标:通过对第一台
alter table test1 add index(name); alter table test2 add index(name);
使用表与订单一起执行一个QEP中加入:
explain select test1.name, test2.name from test1 left join test2 on test1.id=test2.id order by test1.name +----+-------------+-------+--------+---------------+---------+---------+---------------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+---------+---------+---------------+------+-------------+ | 1 | SIMPLE | test1 | index | NULL | name | 21 | NULL | 981 | Using index | | 1 | SIMPLE | test2 | eq_ref | PRIMARY | PRIMARY | 4 | test.test1.id | 1 | | +----+-------------+-------+--------+---------------+---------+---------+---------------+------+-------------+
- 通过
又一次但为了第二张表加入:
explain select test1.name, test2.name from test1 left join test2 on test1.id=test2.id order by test2.name +----+-------------+-------+--------+---------------+---------+---------+---------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+--------+---------------+---------+---------+---------------+------+----------------------------------------------+ | 1 | SIMPLE | test1 | index | NULL | name | 21 | NULL | 981 | Using index; Using temporary; Using filesort | | 1 | SIMPLE | test2 | eq_ref | PRIMARY | PRIMARY | 4 | test.test1.id | 1 | | +----+-------------+-------+--------+---------------+---------+---------+---------------+------+----------------------------------------------+
我不明白为什么查询2使用filesort而查询1能够使用索引。是否有可能遇到本文档中描述的以下限制?
http://dev.mysql.com/doc/refman/5.0/en/order-by-optimization.html
“你在ORDER联接许多表和列BY并不都来自用来检索行的第一个非恒定表(这是EXPLAIN输出,做第一个表没有常量连接类型。)“
请问您是否可以使用预先格式化的文本标签正确格式化?读取SQL输出非常困难。 – 2013-02-08 12:20:38
嗯,试图添加blockquotes,但它仍然搞乱格式化,但在那里有一些奇怪的字符。 – 2013-02-08 12:32:10