《深入理解Mysql》之利用索引排序
阿新 • • 發佈:2018-11-17
使用Mysql的索引進行排序可以大大提高Mysql的效能,使用索引排序的原則是
按照建立索引的順序查詢和排序,執行如下sql
create table t1( id int not null auto_increment, uname varchar(32) not null, tag1 int not null, tag2 int not null, tag3 int not null, PRIMARY KEY(id) ) create index idx_t1_tag1_tag2_tag3 on t1(tag1,tag2,tag3) insert into t1(uname,tag1,tag2,tag3) values ('aaa',11,23,33), ('bbb',12,2,99), ('ccc',9,3,999), ('ddd',99,99,99), ('eee',199,199,199), ('fff',299,299,299), ('ggg',99,19,9), ('hhh',1,4,12), ('jjj',1,3,121), ('kkk',1,3,16), ('lll',1,2,12)
可以看到t1表有一個複合索引,tag1、tag2、tag3,所謂的按照索引順序查詢和排序指在查詢即select列表中按照tag1->tag2->tag3的順序查詢,order by之後一樣
explain select tag1,tag2 from t1 ORDER BY tag1,tag2
如果是where和order by 組合起來後欄位依然是“有序”的,那麼依然會使用索引排序
explain select tag1,tag2 from t1 where tag1 = 1 ORDER BY tag2,tag3