简体   繁体   中英

How can I make this MySQL query more efficient? Subqueries/Left Joins

I'm looking for help with making a query quicker -

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

To give an idea of the application of this query I am using it to populate the parks at this link - http://www.wdwhelper.com . If you need additional info, just let me know.

I am also looking for specific help on subquery T5 - I want to get the most recent (last added to DB) waitTime for each ride - any ideas how this would be possible? Thanks!

Just do one subquery in place of four, and read the table once instead of four times,
and you will save 3/4 (75%) of the time:

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

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