简体   繁体   English

MySQL查询优化左联接索引存在

[英]MySQL query optimization left join indexes exist

I'm struggling with the optimization of a MySQL query. 我正在努力优化MySQL查询。

select * 
from course as t1 
left join semester as t3 on t1.semester=t3.id 
where t1.visibleFrom <= '1364621522' 
and '1364621522' <= t1.visibleTo 
order by t3.begin desc, t1.name;

This is reported by EXPLAIN to use an ALL-query on the course table. EXPLAIN报告这是在课程表上使用ALL查询。 The table has several different indexes (visibleFrom, visibleTo, combination of both, name, semester). 该表具有几个不同的索引(visibleFrom,visibleTo,二者的组合,名称,学期)。 name is a varchar column, begin , visibleFrom and visibleTo are integers that can also be null. name是一个varchar列, beginvisibleFromvisibleTo是整数,也可以为null。

If I leave out the join with t3 and force the use of the index name it works somehow. 如果我省略了与t3并强制使用索引名,它将以某种方式起作用。

Any ideas why this query does not make use of indexes? 有什么想法为什么这个查询不使用索引?

I think the important index for the range restriction in the WHERE is the index on the two columns visibleFrom and visibleTo, ie 我认为WHERE中范围限制的重要索引是visibleFrom和visibleTo两列的索引,即

ALTER TABLE `course` ADD INDEX ( `visibleFrom` , `visibleTo` );

If MySQL doesn't use it in your query, my guess would be that the course table has less than ~ 100 rows. 如果MySQL在查询中不使用它,我猜是课程表少于100行。 Therefore, the MySQL query optimizer decides not to use the index because of the overhead. 因此,由于开销,MySQL查询优化器决定不使用索引。 As soon as the course table contains several hundreds of rows, the index should be used. 课程表一旦包含几百行,就应使用索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM