2010-09-07 114 views
1

我知道這裏有一千個類似的問題,但沒有一個像我一樣處理複雜的查詢(並且我的MySQL技巧並不重要。真正瞭解如何適應它們)優化MySQL查詢以避免「使用臨時」和「使用filesort」

這就是:

explain select 
    `ev`.`EventID` AS `EventID` 
    ,`ev`.`EventName` AS `EventName` 
    ,concat(`ev`.`EventDate`,' ',`ev`.`StartTime`) AS `EventDT` 
    ,`ev`.`NumberTicketsAvailable` AS `TotalTickets` 
    ,`ev`.`Soldout` AS `Soldout` 
    ,count((case when (`ec`.`CartStatus` = 'InCart') then 1 else NULL end)) AS `InCartCount` 
    ,count((case when (`ec`.`CartStatus` = 'InPayment') then 1 else NULL end)) AS `InPaymentCount` 
    ,count((case when (`ec`.`CartStatus` = 'Paid') then 1 else NULL end)) AS `PaidCount` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 604800 second) > now())) then 1 else NULL end)) AS `PaidOverWeek` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 432000 second) > now())) then 1 else NULL end)) AS `PaidOverFiveDays` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 86400 second) > now())) then 1 else NULL end)) AS `PaidOverDay` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 43200 second) > now())) then 1 else NULL end)) AS `PaidOverHalfDay` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 21600 second) > now())) then 1 else NULL end)) AS `PaidOverQuarterDay` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 10800 second) > now())) then 1 else NULL end)) AS `PaidOverThreeHours` 
    ,count((case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 3600 second) > now())) then 1 else NULL end)) AS `PaidOverHour` 
from (`Events` `ev` 
    left join (`Events_EventCart_Rel` `eecr` 
    left join `EventCart` `ec` 
     on((`eecr`.`EventCartID` = `ec`.`EventCartID`))) 
    on((`ev`.`EventID` = `eecr`.`EventID`))) 
where (`eecr`.`Active` = 1 AND `eecr`.`Deleted` = 'No') 
group by 
    `ev`.`EventID` 
    ,`ev`.`EventName` 
    ,`ev`.`EventDate` 
    ,`ev`.`StartTime` 
    ,`ev`.`NumberTicketsAvailable` 
    ,`ev`.`Soldout`; 

這樣做的結果是這樣的:

+-id-+-select_type-+-table-+--type--+--------possible_keys--------+----key----+-key_len-+----------ref----------+--rows--+---------------------------Extra---------------------------+ 
| 1| SIMPLE  | eecr | index | EventID,EventID_2,EventID_3 | EventID_3 | 10  | {null}    | 17609 | Using where; Using index; Using temporary; Using filesort | 
| 1| SIMPLE  | ev | eq_ref | PRIMARY      | PRIMARY | 4  | eecr.EventID   | 1  | Using where            | 
| 1| SIMPLE  | ec | eq_ref | PRIMARY      | PRIMARY | 4  | eecr.EventCartID  | 1  |               | 
+----+-------------+-------+--------+-----------------------------+-----------+---------+-----------------------+--------+-----------------------------------------------------------+ 

而表定義:

CREATE TABLE IF NOT EXISTS `Events` (
    `EventID` int(10) unsigned NOT NULL AUTO_INCREMENT, 
    `EventName` varchar(150) NOT NULL, 
    `StartTime` char(8) NOT NULL DEFAULT '00:00:00', 
    `EndTime` char(8) NOT NULL DEFAULT '00:00:00', 
    `EventDate` varchar(20) NOT NULL, 
    `NumberTicketsAvailable` smallint(6) DEFAULT NULL, 
    `Soldout` enum('yes','no') DEFAULT 'no', 
    #... 
    PRIMARY KEY (`EventID`), 
    KEY `EndTime` (`EndTime`,`EventDate`), 
    KEY `StartTime` (`StartTime`,`EventDate`), 
    KEY `EventDate` (`EventDate`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CREATE TABLE IF NOT EXISTS `Events_EventCart_Rel` (
    `ID` int(11) NOT NULL AUTO_INCREMENT, 
    `EventCartID` int(11) NOT NULL, 
    `EventID` int(11) NOT NULL, 
    `DateAdded` datetime NOT NULL, 
    `PersonID` int(11) NOT NULL, 
    `SeatTypeID` int(11) NOT NULL, 
    `MealChoiceID` int(11) NOT NULL, 
    `Active` tinyint(1) NOT NULL DEFAULT '1', 
    `Deleted` enum('Yes','No') NOT NULL DEFAULT 'No', 
    `ModifiedByAdmin` enum('Yes','No') NOT NULL DEFAULT 'No', 
    PRIMARY KEY (`ID`), 
    KEY `EventID` (`EventID`,`PersonID`), 
    KEY `EventCartID` (`EventCartID`), 
    KEY `EventID_2` (`EventID`), 
    KEY `EventID_3` (`EventID`,`EventCartID`,`Active`,`Deleted`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

CREATE TABLE IF NOT EXISTS `EventCart` (
    `EventCartID` int(11) NOT NULL AUTO_INCREMENT, 
    `RegistrantsID` int(11) NOT NULL DEFAULT '0', 
    `DateRecordCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    `DateRecordModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', 
    `CartStatus` enum('InCart','InPayment','Paid') NOT NULL DEFAULT 'InCart', 
    `ModifiedByAdmin` enum('yes','no') NOT NULL DEFAULT 'no', 
    PRIMARY KEY (`EventCartID`), 
    KEY `rid` (`RegistrantsID`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 

爲了搶佔任何疑惑看待這些列 - 是的,有很多遺留類型的東西,我沒有時間修復代碼。

+0

解釋計劃對我來說聽起來很合理。有什麼困難? – 2010-09-07 15:55:41

+0

這需要約2.5秒。無論如何都不可怕,但我喜歡貪婪。這是針對「實時」報告的,我希望儘可能減少執行時間。 – 2010-09-07 16:03:21

回答

4

我發現至少在MySQL中,幾乎所有使用GROUP BY的查詢都會調用一個臨時表。這是你的巨大性能成本。嘗試研究有它的使用分析器時間花在:

編輯:我修正了以下內容SET PROFILING(不SET PROFILES):

SET PROFILING = On; 
SELECT ...the whole query you want to profile... 
SHOW PROFILES; 
SHOW PROFILE FOR QUERY 1; 

詳情請參閱http://dev.mysql.com/doc/refman/5.1/en/show-profiles.html

沒有太多的事情可以解決這個問題。它有時最好的性能的原因,以消除GROUP BY和聚合函數:

select 
    `ev`.`EventID` AS `EventID` 
    ,`ev`.`EventName` AS `EventName` 
    ,concat(`ev`.`EventDate`,' ',`ev`.`StartTime`) AS `EventDT` 
    ,`ev`.`NumberTicketsAvailable` AS `TotalTickets` 
    ,`ev`.`Soldout` AS `Soldout` 
    ,case when (`ec`.`CartStatus` = 'InCart') then 1 else 0 end AS `InCartCounter` 
    ,case when (`ec`.`CartStatus` = 'InPayment') then 1 else 0 end AS `InPaymentCounter` 
    ,case when (`ec`.`CartStatus` = 'Paid') then 1 else 0 end AS `PaidCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 604800 second) > now())) then 1 else 0 end AS `PaidOverWeekCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 432000 second) > now())) then 1 else 0 end AS `PaidOverFiveDaysCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 86400 second) > now())) then 1 else 0 end AS `PaidOverDayCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 43200 second) > now())) then 1 else 0 end AS `PaidOverHalfDayCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 21600 second) > now())) then 1 else 0 end AS `PaidOverQuarterDayCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 10800 second) > now())) then 1 else 0 end AS `PaidOverThreeHoursCounter` 
    ,case when ((`ec`.`CartStatus` = 'Paid') and ((`ec`.`DateRecordModified` + interval 3600 second) > now())) then 1 else 0 end AS `PaidOverHourCounter` 
from `Events` `ev` 
inner join `Events_EventCart_Rel` `eecr` 
    on `ev`.`EventID` = `eecr`.`EventID` 
inner join `EventCart` `ec` 
    on `eecr`.`EventCartID` = `ec`.`EventCartID` 
where `eecr`.`Active` = 1 and `eecr`.`Deleted` = 'No' 
在應用程序代碼

然後,取所有行,並遍歷它們,計算總計數,當您去。例如,在PHP:

$stmt = $pdo->query($sql); 
$events = array(); 
$counters = array("InCartCounter", "InPaymentCounter", "PaidCounter", 
    "PaidOverWeekCounter", "PaidOverFiveDaysCounter", "PaidOverDayCounter", 
    "PaidOverHalfDayCounter", "PaidOverQuarterDayCounter", 
    "PaidOverThreeHoursCounter", "PaidOverHourCounter"); 

while ($row = $stmt->fetch()) 
{ 
    if (!isset($events[$row["EventID"]])) { 
    $events[$row["EventID"]] = $row; 
    } else { 
    foreach ($counters as $key) { 
     $events[$row["EventID"]][$key] += $row[$key]; 
    } 
    } 
} 

它看起來像一個大量的代碼和麻煩做SQL 應該能夠更有效地做一些事情,但在MySQL和GROUP BY寫更多的情況下,應用程序代碼往往是更好。

PS:在示例SQL查詢中,我將您的連接更改爲內部連接。我不認爲你需要外部連接。

+0

不幸的是,它看起來像我們的MySQL服務器沒有安裝/啓用Profiler(這是正確的版本,但設置PROFILER拋出一個錯誤。)當我們的系統管理員有時間打開它時,我將不得不重新訪問。 – 2010-09-08 20:51:06

+0

我的歉意,我的語法錯了。它是'SET PROFILING = On'。我會在上面編輯我的答案以便正確。 – 2010-09-08 22:58:11

相關問題