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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值