我正在努力优化以下平均需要 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/