优化JOIN子查询中的WHERE子查询

时间:2014-08-08 10:23:58

标签: mysql sql join optimization subquery

SELECT journey.departure AS startTime, departure.duration AS seconds, ADDTIME(journey.departure, departure.duration) AS departureTime, p.section
FROM journey
JOIN journey_day ON journey_day.journey = journey.id
JOIN pattern p ON p.id = journey.pattern
JOIN (
    SELECT departure.section, SEC_TO_TIME(SUM(time)) AS duration
    FROM pattern_link departure
    WHERE departure.from_sequence < (SELECT from_sequence FROM pattern_link WHERE from_stop = "1980SN12532B" AND section = departure.section)
    GROUP BY departure.section
) departure ON departure.section = p.section
WHERE journey.service = "44-A-A-y10-1" AND p.direction = "inbound" AND journey_day.day = 4
GROUP BY journey.id
ORDER BY departure

此查询需要绝对年龄才能运行。这是因为WHERE子查询中JOIN子句中的子查询。问题是,我不知道怎么写它。在离开连接的WHERE语句中,我需要知道from_sequence号码(基本上是ID),我唯一可以做的就是根据WHERE子句中的条件查询。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您的版本将受益于pattern_link(section, from_stop, time)上的索引。该索引可能是改进查询的最简单方法。

您还可以尝试使用聚合将其写为显式join

SELECT departure.section, SEC_TO_TIME(SUM(time)) AS duration
FROM pattern_link departure JOIN
     (SELECT section, from_sequence
      FROM pattern_link
      WHERE from_stop = '1980SN12532B'
     ) s
     ON s.section = departure.section
WHERE departure.from_sequence < s.from_sequence
GROUP BY departure.section