esolve
V2EX  ›  问与答

mysql 中的 where 语句有 and 的话,单列索引不起作用?

  •  
  •   esolve · Sep 30, 2017 · 4101 views
    This topic created in 3175 days ago, the information mentioned may be changed or developed.

    比如

    select * from table where name="apple" and count=3;
    

    如果仅仅对 name 做单列索引,而没有联合索引,我用 explain 发现没有用到索引

    这是怎么回事?

    11 replies    2017-09-30 18:45:47 +08:00
    b821025551b
        1
    b821025551b  
       Sep 30, 2017
    灌进去一千万条数据再试一下。
    xinyewdz
        2
    xinyewdz  
       Sep 30, 2017
    mysql 引擎认为全表扫描比使用索引还快,放弃使用索引
    huigeer
        3
    huigeer  
       Sep 30, 2017
    灌进去 2 千万再试试吧
    esolve
        4
    esolve  
    OP
       Sep 30, 2017
    @b821025551b 目前 5 百多万数据啊,这还不够啊
    miniyao
        5
    miniyao  
       Sep 30, 2017
    @xinyewdz 你这是开玩笑?还是 mysql 真有这么根据查询速度,取舍索引的做法?
    huigeer
        6
    huigeer  
       Sep 30, 2017
    @miniyao mysql 确实会这样的, 它是根据扫描的数据量。
    nandaye
        7
    nandaye  
       Sep 30, 2017 via Android
    如果数据量大且索引出来的量小,那可能是使用了错误的以前的执行逻辑,执行相同的语句数据库不是每次都会取样估计表的数据量,他会使用上次它判断的最优的执行逻辑。
    akira
        8
    akira  
       Sep 30, 2017
    @miniyao 对的。
    如果觉得 mysql 没有正确使用索引,那么可以在 sql 里面指定使用什么索引
    cevincheung
        9
    cevincheung  
       Sep 30, 2017
    @miniyao #5 看 postgresql 的查询计划会更无语的。
    miniyao
        10
    miniyao  
       Sep 30, 2017 via Android
    @huigeer
    @akira
    @cevincheung

    嗯,谢谢,有空去测试观察下😜
    feiyuanqiu
        11
    feiyuanqiu  
       Sep 30, 2017 via Android
    想强制使用索引的话,在查询语句里加上 force index
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1470 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 16:46 · PVG 00:46 · LAX 09:46 · JFK 12:46
    ♥ Do have faith in what you're doing.