V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
aimaodeyuer
V2EX  ›  问与答

有条很简单的 sql explain 后 extra 有不明白的,还望大家指点一二!

  •  
  •   aimaodeyuer · 2020-09-18 14:31:26 +08:00 · 845 次点击
    这是一个创建于 1307 天前的主题,其中的信息可能已经有所发展或是发生改变。
    CREATE TABLE msg (
      id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
      msg_id bigint(20) NOT NULL,
      status tinyint(4),
      content text NOT NULL,
      create_time datetime NOT NULL,
      PRIMARY KEY (id),
      KEY idx_msg_id (msg_id)
    ) ENGINE=InnoDB AUTO_INCREMENT=3048 DEFAULT CHARSET=utf8mb4
    

    select id from msg where msg_id = #{param1} order by id desc limit 10;

    显示走了 idx_msg_id 索引,extra 是 Using where; Using index 。 去掉 order by id 后 ,extra 是 Using index 。

    PS:默认索引扩展 use_index_extensions=on

    Q:既然 idx_msg_id 索引上有 id,且 select 只查询 id,order by id 为何会导致出现 Using where;

    附上 mysql 官方文档:https://dev.mysql.com/doc/refman/5.7/en/index-extensions.html 看完也没弄明白。

    4 条回复    2020-12-15 16:05:29 +08:00
    aimaodeyuer
        1
    aimaodeyuer  
    OP
       2020-09-18 16:22:31 +08:00
    阿,这么久了,没人吗?
    tomy0608
        2
    tomy0608  
       2020-09-18 17:24:23 +08:00
    按照文档上的意思, 就是在你开启了 index_extensions 之后, 会在你自建的索引基础上拓展一个类似联合索引的样子. 从你这个表来说就是 `index(msg_id, id)`.
    执行器器在执行的时候能提高性能. 原话是这样的
    ```
    The optimizer takes into account the primary key columns of the extended secondary index when determining how and whether to use that index. This can result in more efficient query execution plans and better performance.
    ```

    但你这个实际跟这个没啥关系. `Using where` 表示 MySQL 服务器会在搜索引擎执行完之后再进行过滤操作.

    在你没有 order by 时, 直接通过索引定位到了, 所以并不需要过滤操作.(可以这么认为)

    但是你要排序(order by)的话, 是需要基于一个结果排序的, 这个结果便是 Using index 查出来的结果. (虽然你这查出来可能只有一个)
    aimaodeyuer
        3
    aimaodeyuer  
    OP
       2020-09-18 18:05:51 +08:00
    @tomy0608 首先感谢老哥的解答,我先理解一波你的语义

    但是你要排序(order by)的话, 是需要基于一个结果排序的, 这个结果便是 Using index 查出来的结果. (虽然你这查出来可能只有一个)

    1.这个 msg_id 不是唯一键,是多值的。
    2.idx_msg_id 索引是有 id 的值的所以不需要回表,而且是有序的,所以不需要额外的外部排序( Using filesort )
    问题就是我还是不理解何来 using where 一说,不应该直接索引覆盖就完事了吗?
    tomy0608
        4
    tomy0608  
       2020-12-15 16:05:29 +08:00
    @aimaodeyuer 时隔 87 天....我回来了. 平时都在 stackoverflow 上....

    我已经不好意思回复了... , 老哥你应该也用不到了 :-)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5977 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 06:13 · PVG 14:13 · LAX 23:13 · JFK 02:13
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.