mysql - 使用索引优化 MySQL 查询(什么索引?)

标签 mysql performance

我正在努力优化以下平均需要 2000 毫秒的查询。

select  count(pk)
    from  mytable
    where  (pk<>5
      and  url='test.png'
      and  (data=124578 or  (data is null and  pk=1234578)))
      and  type in (123,456,789,015,789) 

这里有一些信息:

select count(*) from mytable

1 526 588行

show indexes in mytable

Table   non_unique  key_name            seq_in_index    column_name collation   cardinality
mytable 0           PRIMARY             1               PK          A           1405079     
mytable 1           data                1               data        A           1405079     
mytable 1           Media_Code_30       1               code        A           1405079     
mytable 1           codeVersionIDX_30   1               code        A           1405079     

解释:

id  select_type table   type        possible_keys   key     key_len ref     rows    extra
1   SIMPLE      mytable ref_or_null PRIMARY,data    data    9       const   635908  Using where

我真的不知道这是否足够优化,或者通过创建新索引(或复合索引)可以更好。

然而,查询无法更改,因为它来自另一个我没有亲 body 验过的系统!

最佳答案

嗯,这个查询似乎很难为以下对象建立索引:

select count(pk)
from mytable
where (pk <> 5 and url = 'test.png' and
       (data = 124578 or (data is null and pk = 1234578))
      ) and
      type in (123, 456, 789, 015, 789);

我的建议是从 type 开始,并在索引中包含其他列:mytable(type, url, data, pk)。这是一个覆盖索引,可能会稍微提高性能。

关于mysql - 使用索引优化 MySQL 查询(什么索引?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37298953/

相关文章:

mysql - 如何正确绑定(bind) MySQL 表

php - Yii框架中的SQL查询帮助(count、group by)!

MySQL 仅导入一列到现有表

php - 使用 PHP + MySQL 切换数据库有多快?

php - 无法让 POST 与 swift 一起工作

mysql - 外键首选字符串还是整数?

c - 提高SQLite每秒INSERT的性能?

javascript - forEach 函数比等效的 for 循环快得多

javascript - 网页上的资源使用

c++ - 在 Debug模式下销毁 Protocol Buffer 消息比在 Release模式下慢近 500 倍