zoukankan      html  css  js  c++  java
  • 为什么会存在using filesort

    当使用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.

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

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

     1。先按照字段k1排序,

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

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

     4。最后是kn

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

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

    但,

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

    3select * from t_talbe where uid!=1 order by id;possible_keysu_f,uidkeynullextraUsing 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

  • 相关阅读:
    字符串替换
    字符串查找
    字符串比较
    字节与字符串相互转换
    1365. How Many Numbers Are Smaller Than the Current Number
    1486. XOR Operation in an Array
    1431. Kids With the Greatest Number of Candies
    1470. Shuffle the Array
    1480. Running Sum of 1d Array
    【STM32H7教程】第56章 STM32H7的DMA2D应用之刷色块,位图和Alpha混合
  • 原文地址:https://www.cnblogs.com/xiaowangba/p/6314174.html
Copyright © 2011-2022 走看看