MySQL倒序如何避免filesort_MySQL Using filesort 疑问?

表及相关数据

create table book(

bid int auto_increment primary key,

`name` varchar(20) not null,

authorid int not null,

publicid int not null,

typeid int not null

);

insert into book values(1,'tjava',1,1,2);

insert into book values(2,'tc',2,1,2);

insert into book values(3,'wx',3,2,1);

insert into book values(4,'math',4,2,3);

需求

查询 authorid =1 且 typeid为2或3的 bid

优化方案

方法1:

索引的顺序是 bid,typeid,authorid

alter table book add index idx_bta (bid,typeid,authorid);

分析结果

explain select bid from book where typeid in(2,3) and authorid=1 order by typeid desc;

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------+

| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------+

| 1 | SIMPLE | book | NULL | index | NULL | idx_bta | 12 | NULL | 4 | 25.00 | Using where; Using index; Using filesort |

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+------------------------------------------+

方法2:

索引的顺序是 typeid,authorid,bid

alter table book add index idx_tab (typeid,authorid,bid);

分析结果

explain select bid from book where typeid in(2,3) and authorid=1 order by typeid desc;

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+--------------------------+

| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+--------------------------+

| 1 | SIMPLE | book | NULL | range | idx_tab | idx_tab | 8 | NULL | 2 | 100.00 | Using where; Using index |

+----+-------------+-------+------------+-------+---------------+---------+---------+------+------+----------+--------------------------+

疑问

为啥索引的顺序是 bid,typeid,authorid 的出现 Using filesort, 而 typeid,authorid,bid却没有出现 Using filesort?


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部