LEFT JOIN延迟查询5秒

时间:2014-08-16 12:39:50

标签: mysql sql

SELECT DISTINCT(journey.id), line.name, journey.departure
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.id
INNER JOIN service ON service.id = journey.service
INNER JOIN operator ON operator.id = service.operator
INNER JOIN line ON line.service = service.id
INNER JOIN pattern ON pattern.id = journey.pattern
INNER JOIN pattern_link pl ON pl.section = pattern.section AND pl.from_stop = "370023292"
INNER JOIN pattern_link pl2 ON pl2.section = pattern.section AND pl2.from_sequence < pl.from_sequence
WHERE journey_day.day = 1 AND CURDATE() BETWEEN service.date_start and service.date_end AND operator.id = "TMTL"
ORDER BY journey.departure

以上是MySQL查询,运行大约需要0.05秒。

只要我追加LEFT JOIN journey_code ON journey_code.journey = journey.id,它就会在查询中再添加4-6秒。我觉得这与journey.id子句中对ON列的第二次引用有关。为什么这个LEFT JOIN会延迟查询结果呢?

有关journey_code表的信息:

id(INT 11 PK AI) | journey(VARCHAR 128) | code(VARCHAR 16)

journeycode都有索引。我已经尝试了两者的综合索引,这并没有以任何方式加快查询速度。

查询前面加EXPLAIN的结果:http://i.imgur.com/BVrm9qv.png

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

尝试将上述查询作为子查询:

SELECT j.*, jc.<whatever>
FROM (SELECT DISTINCT journey.id, line.name, journey.departure
      FROM journey
      INNER JOIN journey_day ON journey_day.journey = journey.id
      INNER JOIN service ON service.id = journey.service
      INNER JOIN operator ON operator.id = service.operator
      INNER JOIN line ON line.service = service.id
      INNER JOIN pattern ON pattern.id = journey.pattern
      INNER JOIN pattern_link pl ON pl.section = pattern.section AND pl.from_stop = "370023292"
      INNER JOIN pattern_link pl2 ON pl2.section = pattern.section AND pl2.from_sequence < pl.from_sequence
      WHERE journey_day.day = 1 AND
            CURDATE() BETWEEN service.date_start and service.date_end AND
            operator.id = 'TMTL'
    ) j left join
    journey_code jc
    ON jc.journey = j.id
ORDER BY j.departure

MySQL工作的方式,它应该运行子查询并实现它。如果您在journey_code(journey)上有索引,那么加入应该很快。