mysql 在查询时 如果查询语句中犹豫某些原因未使用到索引,导致查询很慢,可以强制使用索引。
如
EXPLAIN
SELECT cr.id
FROM car_record cr
LEFT JOIN camera c ON cr.camera_id=c.id
LEFT JOIN pile p ON p.pile_id=c.pile_id
LEFT JOIN station s ON c.station_id=s.station_id
LEFT JOIN county co ON s.county_code=co.code
LEFT JOIN city ci ON s.city_code=ci.code
WHERE cr.is_delete = 0
ORDER BY cr.created_time DESC
语句中 car_record cr 中created_time为索引字段
但在查询过程中,索引并未生效
原因:
多表联查,产生了临时表,而对结果的排序使用了文件排序
解决:
一般我们在进行查询的时候,排序字段是要加索引并要使其生效的。
所以,我们可以使用FORCE INDEX(idx_name),让查询强制使用指定的索引
EXPLAIN
SELECT cr.id
FROM car_record cr FORCE INDEX(created_time)
LEFT JOIN camera c ON cr.camera_id=c.id
LEFT JOIN pile p ON p.pile_id=c.pile_id
LEFT JOIN station s ON c.station_id=s.station_id
LEFT JOIN county co ON s.county_code=co.code
LEFT JOIN city ci ON s.city_code=ci.code
WHERE cr.is_delete = 0
ORDER BY cr.created_time DESC
这样,created_time索引就生效了。
Explain中 Extra中一些关键词的说明:
useing index: 是指用到了索引覆盖,效率非常高
using where 是指光靠索引定位不了,还得where判断一下
Distinct:MySQL发现第1个匹配行后,停止为当前的行组合搜索更多的行。
Not exists:MySQL能够对查询进行LEFT JOIN优化,发现1个匹配LEFT JOIN标准的行后,不再为前面的的行组合在该表内检查更多的行。
range checked for each record (index map: #):MySQL没有发现好的可以使用的索引,但发现如果来自前面的表的列值已知,可能部分索引可以使用。
Using filesort:MySQL需要额外的一次传递,以找出如何按排序顺序检索行。
Using temporary:为了解决查询,MySQL需要创建一个临时表来容纳结果。
Using sort_union(...), Using union(...), Using intersect(...):这些函数说明如何为index_merge联接类型合并索引扫描。
Using index for group-by:类似于访问表的Using index方式,Using index for group-by表示MySQL发现了一个索引,可以用来查 询GROUP BY或DISTINCT查询的所有列,而不要额外搜索硬盘访问实际的表。