› 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
cc959798
V2EX  ›  MySQL

请问 mysql 不使用索引排序的话改怎么优化

  •  
  •   cc959798 · Nov 14, 2018 · 3727 views
    This topic created in 2915 days ago, the information mentioned may be changed or developed.

    比如我们一条 sql

    select * from tb where id=xxx order by create_time desc limt 0,20

    id 和 create_time 都是有索引的

    但是 where 限定里面使用的 id,就会走 id 这个索引了,但是我们业务上需要用 create_time 排序,因为要取前 20 条,这个 sql 怎么优化会快些呢?

    另外不使用索引排序的话 mysql 是怎么排序的? 把结果集加载到内存中进行排序吗?

    另外不使用索引排序的话一般会 using filesort 的,但是我 explain 一下的话结果发现没有这个,这是为什么呢

    8 replies  •  2018-11-15 09:28:25 +08:00
    xiaoxinshiwo
    xiaoxinshiwo
    Nov 14, 2018
    1
    force index ?
    wps353
    wps353
    Nov 14, 2018
    2
    add index idx_id_createtime(id,create_time)
    cc959798
    cc959798
    OP
    Nov 14, 2018
    3
    @wps353 额,有其他办法吗?另外不使用索引排序,mysql 就是在内存里排序的吗
    ppyybb
    ppyybb
    Nov 14, 2018 via iPhone
    4
    是否加载到内存不好说,有可能进行外部排序,这个应该根据结果集的数据量来的。

    你需要把 explain 所有的结果打出来,以及有的索引拿出来才好分析为什么没有 filesort。

    你没有权限给数据库加索引,就看看 id=xxx 的数据量有多大,不是很大的话可以考虑自己全部加载回来到服务器上自己排序。或者有没有什么业务信息可以确实前 20 条的大致范围,这样可以过滤一部分再自己排序。

    如果考虑不让它走 id 这个索引,那么考虑强制直接走 created 的索引效果应该不好,因为它需要把所有数据都排序,然后过滤对应的 id,大概率优化器不会采取这个 hint 的。
    Raymon111111
    Raymon111111
    Nov 14, 2018
    5
    尝试加一个索引 id, ctime

    但是看起来你这个 id 对应的数据很多, 一般的方法基本都不会太好用 2333
    msg7086
    msg7086
    Nov 15, 2018
    6
    你没有 id,ctime 索引的话 MySQL 怎么去用 ctime 索引跑啊。如上面所说,先排序 ctime,然后扫全表过滤 id 吗?怕不是比你现在的还慢几个数量级哦。
    agostop
    agostop
    Nov 15, 2018
    7
    没用 ctime,证明 mysql 认为用全表遍历比较快,可以试试 force index
    agostop
    agostop
    Nov 15, 2018
    8
    你们 id 如果是自增的话,按道理用 id 也可以啊,除非你 ctime 是可以编辑的……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1906 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 08:33 · PVG 16:33 · LAX 00:33 · JFK 03:33
    ♥ Do have faith in what you're doing.