› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
xing393939
V2EX  ›  MySQL

请问一个 order by 使用索引的问题

  •  
  •   xing393939 ·
    xing393939 · Sep 23, 2024 · 3330 views
    This topic created in 731 days ago, the information mentioned may be changed or developed.

    请问当联合索引是 a,b 时,这 2 个 sql 有啥区别吗:

    select * from t where a=1 order by b ASC
    select * from t where a=1 order by b DESC
    
    11 replies  •  2024-09-23 14:09:50 +08:00
    gaogao321
        1
    gaogao321  
       Sep 23, 2024   ❤️ 1
    1 、第一个 SQL 语句( order by b ASC )可以直接利用联合索引 (a, b),因此性能较好。
    2 、第二个 SQL 语句( order by b DESC )可能无法完全利用索引 (a, b),需要额外的排序操作,性能可能稍差。
    sagaxu
        2
    sagaxu  
       Sep 23, 2024
    返回结果顺序不同,排序跟物理存储顺序一致的,性能可能会略高,顺序读一般比倒序读更快。

    但在索引使用上没有区别,整体性能差异不大。
    8355
        3
    8355  
       Sep 23, 2024
    我看了半天这两个 sql ,真的陷入沉思。。
    真没想到你会问 asc 和 desc 。。。
    gaogao321
        4
    gaogao321  
       Sep 23, 2024   ❤️ 1
    如果你经常需要对 b 列进行降序排序,可以考虑创建一个复合索引 (a, b DESC),这样在执行 order by b DESC 时也能充分利用索引,避免额外的排序操作。
    coderzhangsan
        5
    coderzhangsan  
       Sep 23, 2024
    如#2 所说 创建索引如果不指定排序 默认是升序 因此第二个 SQL 语句相较于第一个 SQL 语句 额外多了一层排序开销 其他与第一个 SQL 语句一致
    seedhk
        6
    seedhk  
       Sep 23, 2024
    一直没关注到排序顺序这点对索引的影响,学习了
    cnoder
        7
    cnoder  
       Sep 23, 2024
    8.0 文档上写:
    MySQL 降序索引简介
    降序索引是以降序存储键值的索引。在 MySQL 8.0 之前,您可以 DESC 在索引定义中指定。但是,MySQL 忽略了它。与此同时,MySQL 可以以相反的顺序扫描索引,但成本很高。

    所以说 8 之前的知识能这么写但是没有用,另外也标注了反序扫描成本高
    freemoon
        8
    freemoon  
       Sep 23, 2024
    索引默认按 ASC ,但可以修改为 DESC 。
    rrfeng
        9
    rrfeng  
       Sep 23, 2024
    逆序 != 排序

    我认为可以忽略
    phithon
        10
    phithon  
       Sep 23, 2024
    才知道这一点,学习了
    sagaxu
        11
    sagaxu  
       Sep 23, 2024   ❤️ 2
    @gaogao321
    @coderzhangsan
    @cnoder

    根据 https://dev.mysql.com/doc/refman/8.4/en/order-by-optimization.html#order-by-index-use

    SELECT * FROM t1
    WHERE key_part1 = constant
    ORDER BY key_part2;

    SELECT * FROM t1
    WHERE key_part1 = constant
    ORDER BY key_part2 DESC;

    以上两个查询都不会产生 filesort ,有没有 DESC 都一样

    根据 https://dev.mysql.com/blog-archive/mysql-8-0-labs-descending-indexes-in-mysql/
    由于单向链表不能直接回溯,正向扫描比反向扫描快 15%左右
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   843 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 20:44 · PVG 04:44 · LAX 13:44 · JFK 16:44
    ♥ Do have faith in what you're doing.