2014-04-03 61 views
2
SELECT TIME(ADDTIME(departure, SEC_TO_TIME(SUM(jptl2.run_time)))) AS departure, 
     service.line_name AS line, 
     bus.registration 
FROM vehicle_journey 
LEFT JOIN bus ON bus.journey = vehicle_journey.code AND 
      ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) > vehicle_journey.departure AND 
      ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) < ADDTIME(vehicle_journey.departure, SEC_TO_TIME(SUM(jptl.run_time))) 
INNER JOIN service ON service.reference = vehicle_journey.service_reference 
INNER JOIN vehicle_journey_days ON vehicle_journey_days.journey_reference = vehicle_journey.reference 
INNER JOIN journey_pattern ON journey_pattern.reference = vehicle_journey.journey_pattern_reference 
INNER JOIN journey_pattern_timing_link jptl ON jptl.section = journey_pattern.journey_pattern_section 
INNER JOIN journey_pattern_timing_link jptl2 ON jptl2.section = journey_pattern.journey_pattern_section AND jptl2.ID < jptl.id 
WHERE jptl.stop = '1900HA030334' AND vehicle_journey_days.day = 'MondayToFriday' 
GROUP BY vehicle_journey.id 

上面的SQL查詢返回的:#1111 - Invalid use of group functionSQL無效使用組功能

我知道,這個問題是由第三ONLEFT JOIN bus子句中造成的。我該如何重寫查詢,以便根據相同的要求保存相同的目的和連接,但沒有組功能錯誤?

我可以直接將SEC_TO_TIME(SUM(jptl.run_time))作爲子查詢嗎?
EG:(SELECT SEC_TO_TIME(SUM(jptl.run_time)))

回答

0

你不能在[LEFT] JOIN條件下使用一組功能,因爲在這個階段,該集團仍在被構造(進程,這些羣體的內容依賴於連接條件,所以這會創建一種循環引用)。

首先構建您的組,然後再加入依賴於這些羣體的表:

SELECT groups.*, bus.registration 
FROM (
    SELECT 
     TIME(...) AS departure, 
     service.line_name AS line, 
     ADDTIME(vehicle_journey.departure, SEC_TO_TIME(SUM(jptl.run_time))) 
      AS upper_limit, 
     vehicle_journey.code 
      AS vj_code, 
     vehicle_journey.departure 
      AS vj_departure 
    FROM vehicle_journey 
    -- skip "bus" for now 
    JOIN service ... 
    -- add all remaining JOIN's here 
    WHERE ... 
    GROUP BY vehicle_journey.id 
) AS groups 
LEFT JOIN bus 
    ON bus.journey = vj_code 
    AND ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) > vj_departure 
    AND ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) < upper_limit; 

你也可以簡單的把問題的條件下,以一個HAVING條款,但是這不會與不匹配在返回記錄bus(有效地將LEFT JOIN變成INNER JOIN):

SELECT 
    ... 
FROM vehicle_journey 
LEFT JOIN bus ON bus.journey = vehicle_journey.code AND 
     ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) > vehicle_journey.departure 
     -- no reference to "SUM(jptl.run_time)" here 
JOIN service ... 
WHERE ... 
GROUP BY vehicle_journey.id 
-- and here is the reference to "SUM(jptl.run_time)" 
HAVING ADDTIME(TIME(NOW()), SEC_TO_TIME(3600)) 
     < ADDTIME(vehicle_journey.departure, SEC_TO_TIME(SUM(jptl.run_time)))