2015-06-12 102 views
0

我在尋找幫助,使查詢更快 -如何讓這個MySQL查詢更高效?子查詢/左加入

SELECT DISTINCT waits.ride, 
       T2.daywait, 
       T3.timewait, 
       T4.daytimewait, 
       T5.currentwait 
FROM waits 
     left join (SELECT Avg(waittime) AS dayWait, 
         ride 
        FROM waits 
        WHERE dayofweek = '" . $dow . "' 
        GROUP BY ride) AS T2 
       ON T2.ride = waits.ride 
     left join (SELECT Avg(waittime) AS timeWait, 
         ride 
        FROM waits 
        WHERE currenttime >= '" . $minusTime . "' 
         AND currenttime <= '" . $plusTime . "' 
        GROUP BY ride) AS T3 
       ON T3.ride = waits.ride 
     left join (SELECT Avg(waittime) AS dayTimeWait, 
         ride 
        FROM waits 
        WHERE currenttime >= '" . $minusTime . "' 
         AND currenttime <= '" . $plusTime . "' 
         AND dayofweek = '" . $dow . "' 
        GROUP BY ride) AS T4 
       ON T4.ride = waits.ride 
     left join (SELECT waittime AS currentWait, 
         ride 
        FROM waits 
        GROUP BY ride 
        ORDER BY wid DESC) AS T5 
       ON T5.ride = waits.ride 
WHERE park = '" . getPark() . "' 

http://pastebin.com/DDSpGFWQ

爲了讓這個查詢的應用程序的想法,我用它來填充這個公園鏈接 - http://www.wdwhelper.com。如果您需要更多信息,請告訴我。

我也在尋找子查詢T5的具體幫助 - 我想獲得最新的(最後添加到數據庫)waitTime每個騎 - 任何想法如何這將是可能的?謝謝!

回答

0

只是做一個子查詢代替4個,讀取表一次,而不是四倍,
,你將節省3/4(75%)的時間:

SELECT ride , 
    Avg(CASE WHEN dayofweek = '" . $dow . "' THEN waittime END) AS dayWait, 
    Avg(CASE WHEN currenttime >= '" . $minusTime . "' 
        AND currenttime <= '" . $plusTime . "' 
     THEN waittime END) AS dayWait, 
    Avg(CASE WHEN currenttime >= '" . $minusTime . "' 
        AND currenttime <= '" . $plusTime . "' 
        AND dayofweek = '" . $dow . "' 
     THEN waittime END) AS dayWait, 
    waittime AS currentWait      
FROM waits 
GROUP BY ride