在结果中包含ORDER BY列时避免使用filesort

时间:2015-02-27 14:33:30

标签: mysql join query-performance

对于医疗日历,我有以下问题:

SELECT
   `events`.`StartDate`,
   `events`.`ID`,
   `events`.`EndDate`,
   `events`.`Title`,
   `insurances`.`Title`,
   `personsPatients`.`PrimaryPhone`,
   `personsDocs`.`Name`

FROM `events`

LEFT JOIN `events++persons` ON `events`.`ID` = `events++persons`.`FirstEntityID` AND `events++persons`.`Type` = 'Patient'
LEFT JOIN `persons` AS `personsPatients` ON `events++persons`.`SecondEntityID` = `personsPatients`.`ID`
LEFT JOIN `insurances` ON `persons`.`Provider` = `insurances`.`ID`
LEFT JOIN `events++persons` AS `events++persons1` ON `events`.`ID` = `events++persons1`.`FirstEntityID` AND `events++persons1`.`Type` = 'Doctor'
LEFT JOIN `persons` AS `personsDoctors` ON `events++persons`.`SecondEntityID` = `personsDoctors`.`ID`
LEFT JOIN `companies++events` ON `events`.`ID` = `companies++events`.`SecondEntityID` 

WHERE
   ((`events`.`Type` = 'Annotation' and `companies++events`.`FirstEntityID` IS NULL) or 
    (`events`.`Type` = 'Annotation' and `companies++events`.`FirstEntityID` = 1) or 
    (`events`.`Type` = 'Consultation' and `companies++events`.`FirstEntityID` = 1)) and 

    `events`.`StartDate` >= '2015-03-02 00:00:00' AND 
    `events`.`StartDate` <= '2015-03-07 23:59:59'

ORDER BY `events`.`StartDate` ASC

事件通过events++persons与两个人联系:医生和病人。

此查询非常慢。

enter image description here

当我删除ORDER BY(这是必不可少的)时,filesort和temp表就会消失。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

问题在于companies++events - 当标准仅在结束时,世界上所有的一对一LEFT JOIN都无济于事。我设法将该信息移动到主实体(有点像指针)并创建覆盖索引,现在查询是闪电般的。