账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    using filesort 和 using temporary 的使用场景?
    • 2019-01-08 00:00
    • 10
    79
    0

    问题源自这篇文章:MySQL · 答疑释惑· using filesort VS using temporary

    文章中:

    create table t1(    
    id int, col1 int, col2 varchar(10),
    key(id, col1));
    
    create table t2(
    id int, col1 int, col2 varchar(10),
    key(col1));

    case2:

    mysql> explain select * from t1 force index(id), t2 where t1.id=1 and t1.col1 = t2.col2 order by t1.col2;
    +----+-------------+-------+------+---------------+------+---------+-------+------+-----------------------------+
    | id | select_type | table | type | possible_keys | key  | key_len | ref   | rows | Extra                       |
    +----+-------------+-------+------+---------------+------+---------+-------+------+-----------------------------+
    |  1 | SIMPLE      | t1    | ref  | id            | id   | 5       | const |    1 | Using where; Using filesort |
    |  1 | SIMPLE      | t2    | ALL  | NULL          | NULL | NULL    | NULL  |    1 | Using where                 |
    +----+-------------+-------+------+---------------+------+---------+-------+------+-----------------------------+

    case3:

    mysql> explain select * from t1 force index(id), t2 where t1.id=1 and t1.col1 = t2.col2 order by t2.col1 ;
    +----+-------------+-------+------+---------------+------+---------+-------+------+----------------------------------------------+
    | id | select_type | table | type | possible_keys | key  | key_len | ref   | rows | Extra                                        |
    +----+-------------+-------+------+---------------+------+---------+-------+------+----------------------------------------------+
    |  1 | SIMPLE      | t1    | ref  | id            | id   | 5       | const |    1 | Using where; Using temporary; Using filesort |
    |  1 | SIMPLE      | t2    | ALL  | NULL          | NULL | NULL    | NULL  |    1 | Using where; Using join buffer               |
    +----+-------------+-------+------+---------------+------+---------+-------+------+----------------------------------------------+

    文章结论:

    case2: order by谓词,是在第一个表t1上完成,所以只需要在t1表上使用filesort,然后排序后的结果集join t2表。
    case 3: order by的字段在t2表上,所以需要把t1,t2表join的结果保存到temporary表上,然后对临时表进行filesort,最后输出结果。

    我的问题:

    为什么case2 case3都需要做join,为什么case3需要保存到temporary表,而case2不需要呢??
    请大佬解惑。

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部