[英]MySQL query using filesort and temporary
I am using a simple MySQL query, but the performance is realy bad because of using ORDER BY. 我使用的是一个简单的MySQL查询,但由于使用了ORDER BY,性能确实很差。 I can't figure out why MySQL is using filesort and temporary. 我无法弄清楚为什么MySQL使用filesort和临时。
My query is: 我的查询是:
EXPLAIN
SELECT * FROM Events
INNER JOIN EventLogFiles ON ServerID = 42
AND Events.LogFileID = EventLogFiles.LogFileID
ORDER BY ReportID DESC , TimeWritten DESC
LIMIT 100
This is the output of EXPLAIN: 这是EXPLAIN的输出:
Table Events structure 表事件结构
Table Events indexes 表事件索引
Table EventLogFiles structure 表EventLogFiles结构
Table EventLogFiles indexes 表EventLogFiles索引
UPDATE: 更新:
I tried to create two new indexes, but both still force MySQL to use filesort and temporary. 我试图创建两个新索引,但两者仍然迫使MySQL使用filesort和临时。
ALTER TABLE Events ADD INDEX `ReportID_TimeWritten_ServerID_LogFileID` ( ReportID DESC, TimeWritten DESC, ServerID, LogFileID)
ALTER TABLE Events ADD INDEX `ServerID_LogFileID_ReportID_TimeWritten` ( ServerID, LogFileID, ReportID DESC, TimeWritten DESC)
In order to utilize the index for both selection and sorting, you need to have all of the following columns in a multi-column index on Events: (ServerID, LogFileID, ReportID, TimeWritten)
. 为了利用索引进行选择和排序,您需要在事件的多列索引中包含以下所有列: (ServerID, LogFileID, ReportID, TimeWritten)
。
Currently, MySQL cannot utilize the existing multi-column index because it doesn't include LogFileID
, which is in your ON
clause. 目前,MySQL不能利用现有的多列索引,因为它不包括LogFileID
,这是你在ON
子句。
If you ever have problems where MySQL is selecting from EventLogFiles first, you can change the INNER JOIN
to a STRAIGHT JOIN
to ensure that MySQL always elects from Events first, using your index. 如果您遇到MySQL首先从EventLogFiles中选择的问题,您可以将INNER JOIN
更改为STRAIGHT JOIN
以确保MySQL始终首先使用您的索引从事件中选择。
为了在没有临时表和文件排序的情况下工作,您必须创建索引(ServerID, LogFileID, ReportID)
并且TimeWritten
必须像您在ReportID
使用的auto_increment
一样顺序,因此制作ORDER BY ReportID(PK - Order Physical)
您必须删除filesort。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.