我知道有一千个类似的问题,我读了很多,但我不知道如何提高以下查询的性能:
SELECT DATE_FORMAT(c.date, "%d/%m/%Y") AS ddmmyy, c.idQualification, q.name,
SUM(idContactList = "") + COUNT( DISTINCT NULLIF( CONCAT( c.idContactList, c.idActivity ), "" ) ) AS numCalls
FROM callsBreakdown c
LEFT JOIN qualification q ON q.idQualification = c.idQualification
LEFT JOIN activityCampaign a ON (a.idActivity = c.idActivity)
LEFT JOIN qualificationCampaign qc ON (qc.idCampaign = a.idCampaign AND qc.idQualification = c.idQualification)
WHERE c.date BETWEEN "2011-01-01" AND "2012-10-01"
GROUP BY c.date, q.name
如果日期范围很宽,例如1年或更长时间,则查询需要10-12秒才能完成。在EXPLAIN中关于callsBreakdown表(其他人在Extra列中有“使用索引”并且它们很快):
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE c ALL date NULL NULL NULL 379553 Using where; Using temporary; Using filesort
服务器不使用日期索引,需要临时表和filesort。任何的想法?谢谢!
编辑:我将别名“date”更改为“ddmmyy”,结果相同。别名不是问题。
编辑2:如果日期范围是两个月或更短,MySQL使用日期索引(键)代替“NULL”键
答案 0 :(得分:1)
当你写GROUP BY date
时,它使用别名,这是函数调用的输出:
SELECT DATE_FORMAT(c.date, "%d/%m/%Y") AS date, ...
请尝试按原始表中的列进行分组,这应该允许ORDER BY使用索引:
GROUP BY c.date, q.name