[英]Why MySql doesn't use my index and how to avoid the “Using temporary; Using filesort”?
I have a MySql query that looks like the following: 我有一个MySql查询,如下所示:
SELECT trace_access.Employe_Code, trace_access.Employe_Prenom,
trace_access.Employe_Nom, , trace_access.Evenement_Date, trace_access.Evenement_Heure
FROM trace_access
INNER JOIN emp
ON trace_access.Employe_Code = emp.Employe_CodeEmploye
LEFT JOIN user
ON emp.Employe_ID = user.Employe_ID
LEFT JOIN role
ON role.User_ID = user.User_ID
WHERE trace_access.Employe_Nom Not Like "TEST%NU"
ORDER BY trace_access.Evenement_Date DESC , trace_access.Evenement_Heure DESC
The table "trace_access"contains almost 20 million entries. 表“ trace_access”包含将近2000万个条目。
When I explain the query: 当我解释查询时:
My question is why MySql didn't use the key for the emp table and how to avoid "Using temporary; Using filesort" ?? 我的问题是,为什么MySql不使用emp表的键,以及如何避免“使用临时;使用文件排序”?
I have tried to froce it to use my index but that didn't work. 我尝试过使用它来使用索引,但这没有用。 The query lasts one hour and more, writes a file on /tmp folder that exceeds 8Go !!!
查询持续一小时或更长时间,在/ tmp文件夹中写入一个超过8Go的文件!
Any help ? 有什么帮助吗?
Thanks a lot. 非常感谢。
With your current execution plan (to start with emp
), a full table scan is required and there is no usefull index on emp
. 根据您当前的执行计划(以
emp
开头),需要进行全表扫描,并且emp
上没有有用的索引。 This can make sense when you only get a relatively small amount of rows after your join
to trace_access
, which probably isn't the case here. 当您
join
trace_access
之后仅获得相对较少的行时,这可能是trace_access
,这里可能不是这种情况。
To prevent the filesort
, you need an index that supports your order by
. 为了防止
filesort
,你需要一个支持你的索引order by
。 So add, if it doesn't exist yet, the index trace_access(Evenement_Date, Evenement_Heure)
. 因此,如果还不存在,请添加索引
trace_access(Evenement_Date, Evenement_Heure)
。
This might already be enough to make MySQL start with trace_access
. 这可能已经足以使MySQL以
trace_access
。 If not, replace INNER JOIN emp
with STRAIGHT_JOIN emp
. 如果不是,请将
INNER JOIN emp
替换为STRAIGHT_JOIN emp
。 This will force MySQL to do so. 这将迫使MySQL这样做。
Also add an index for emp(Employe_CodeEmploye)
. 同时为
emp(Employe_CodeEmploye)
添加一个索引。
Depending on your data, you can try to add Employe_Code
and/or Employe_Nom
as 3rd and/or 4th column to the index on trace_access
, though it will probably not have much effect. 根据您的数据,您可以尝试将
Employe_Code
和/或Employe_Nom
作为第三列和/或第四列添加到trace_access
的索引中,尽管可能不会产生太大影响。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.