欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

为什么会存在usingfilesort

程序员文章站 2023-12-30 15:51:52
...

当使用explain分析SQL时常常会遇到extra的其中一为using filesort,如: PRIMARY KEY (`id`), KEY `uid` (`uid`) explain select * from t_talbe where uid=1order by id; extra结果为:Using where; Using filesort 手册中对Using filesort解释是“MySQLmust

当使用explain分析SQL时常常会遇到extra的其中一值为using filesort,如:

PRIMARY KEY (`id`),
KEY `uid` (`uid`)

explain select * from t_talbe where uid=1order by id;

extra结果为:Using where; Using filesort

手册中对Using filesort解释是“MySQLmust do an extra pass to find out how to retrieve the rows in sorted order. Thesort is done by going through all rows according to the join type and storingthe sort key and pointer to the row for all rows that match the WHERE clause.”。

假设根据条件会得到两条记录A(id1,uid1,*)和B(id2,uid2,*);根据KEY `uid` (`uid`)排序规则,很容易得到这两条结果,找到的两个uid,即uid1和uid2,它们被检索出来的先(假如uid1)后(假如uid2)顺序已经知道了它们之间的大小关系,然而,id1和id2,谁大谁小呢?不知道。必须在它们之间进行比较,如果有n条结果集,必须对它们全部取出来比较,才能知道第一个记录是哪一个。第二个,……第n个呢?

现在先来了解一下index的一个思想,假设有“KEY key_name(`k1`,`k2`,……,`kn`)”,我们知道记录集会:

1。先按照字段k1排序,

2。在k1相同的情况下,按k2排序,

3。在k2也相同的情况下,再按k3排序,依此类推,

4。最后是kn。

由此规则下可知,在一个队列Lx中,存在两个邻近的点Li(ki,1,ki,2,……,ki,n)和Li+1(ki+1,1,ki+1,2,……,ki+1,n),如果ki,1=ki+1,1,那么知道ki,2和ki+1,2在不需要比较的情况下就可以知道它们之间的关系。

所有针对以上的例子,把KEY `uid` (`uid`)修改成KEY `u_id` (`uid`,`id`)可得以解决。

但,

例2。select * from t_talbe where uid=1 order by id,uid;还是没办法,因为不可能建立INDEX `u_id_u` (`uid`,`id`,`uid`);

例3。select * from t_talbe where uid!=1 order by id;(possible_keys:u_f,uid;key:null;extra:Using where; Using filesort。)

其中:uid=2(id|1,2,3,4),和uid=3(id|1,2,3,4),为了得到id的排序,对于`u_id`(`uid`,`id`)还得把所有记录取出来比较。

顺便说一下,有时候存在Using filesort,也未必是什么大不了的:如

例4。 select * from t_talbe order by id;只是告诉你它使用了“all rows”。

上一篇:

下一篇: