Zereker

问题分析

  • 所遇情况:

    1. 数据库版本:5.6.38
    2. 查询时使用时间类型,在status、closed、playback_state字段上都有索引
    3. 几种查询语句
      explain (select count(*)
               from session
               where status = 2
                 and playback_state = 1
                 and closed > \'2018/10/17\'
                 and closed < \'2018-10-18\');
      explain (select count(*)
               from session
               where status = 2
                 and playback_state = 1
                 and closed like \'2018-10-17%\');
      explain (select count(*)
               from session
               where status = 2
                 and playback_state = 1
                 and closed > 1539705600
                 and closed < 1539792000);
      explain (select count(*)
               from session
               where status = 2
                 and playback_state = 1
                 and closed > unix_timestamp(\'2018/10/17\')
                 and closed < unix_timestamp(\'2018-10-18\'));
    4. 查询情况:第一种情况使用closed的索引,查询速度很快. 其他使用playback_state,因为playback_state相同的数据有很多,因此除第一种情况外,其他情况都很糟糕。
  • 为什么其他几种情况未使用closed进行索引:

    1. mysql查询时,不管有多少个单个索引或联合索引,永远只使用一个索引。

    2. 具体使用哪个索引进行查询,由mysql进行选择,会选择一个它认为最合适的一个字段。在以上情况中,其选择了playback_state,而非closed。

  • 应对方案:

    1. 当语句执行太长时间,使用explain看一下查询情况,mysql是否使用了正确的索引。
    2. 在有索引的字段上使用函数是会把索引去掉的。
    3. 可以使用use index强制mysql使用固定索引
    4. 可以考虑使用联合索引(开发不能随意改动数据库的表结构)

分类:

技术点:

相关文章: