简体   繁体   中英

MySQL query using filesort and temporary

I am using a simple MySQL query, but the performance is realy bad because of using ORDER BY. I can't figure out why MySQL is using filesort and temporary.

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:

Mysql 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.

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) .

Currently, MySQL cannot utilize the existing multi-column index because it doesn't include LogFileID , which is in your ON clause.

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.

为了在没有临时表和文件排序的情况下工作,您必须创建索引(ServerID, LogFileID, ReportID)并且TimeWritten必须像您在ReportID使用的auto_increment一样顺序,因此制作ORDER BY ReportID(PK - Order Physical)您必须删除filesort。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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