MySQL添加连接会降低整个查询的速度

时间:2014-12-27 10:52:23

标签: mysql sql join innodb

SELECT journey.code, journey.departure, journey.end, group_concat(pattern_road.latitude)
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.code
INNER JOIN pattern ON pattern.code = journey.pattern
LEFT JOIN pattern_road ON pattern_road.section = pattern.section
WHERE journey_day.day = 5 AND TIME(NOW()) BETWEEN journey.departure AND journey.end
GROUP BY journey.code

上述查询大约需要100毫秒才能执行。我对此很满意,但我现在需要添加另一个连接,当我尝试这样做时,查询会减慢到大约2秒。

这是带有额外连接的新慢查询:

SELECT journey.code, journey.departure, journey.end, group_concat(pattern_road.latitude) AS road, group_concat(link.stop) AS stop
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.code
INNER JOIN pattern ON pattern.code = journey.pattern
LEFT JOIN pattern_road ON pattern_road.section = pattern.section
INNER JOIN link ON link.section = pattern.section
WHERE journey_day.day = 5 AND TIME(NOW()) BETWEEN journey.departure AND journey.end
GROUP BY journey.code

注意事项:

额外连接也在与前一个连接(pattern_road)连接的同一列上运行,我只能认为这必然是问题的原因。例如,如果我用链接连接替换pattern_road join,则查询返回到100ms,我只是不能使用两个连接并让它以100ms运行。

Database schematic/indexes in SQL Fiddle

为什么会发生这种情况?提前谢谢。

2 个答案:

答案 0 :(得分:0)

你能这样试试吗?

SELECT  SQL_NO_CACHE journey.code, journey.departure, journey.end,
  (select group_concat(pattern_road.latitude) from  pattern_road where pattern_road.section = pattern.section) AS road,
  (select group_concat(link.stop) from link where link.section = pattern.section) AS stop
FROM journey
INNER JOIN journey_day ON journey_day.journey = journey.code
INNER JOIN pattern ON pattern.code = journey.pattern
WHERE journey_day.day = 5 AND TIME(NOW()) BETWEEN journey.departure AND journey.end
GROUP BY journey.code            

答案 1 :(得分:0)

请记住,两列上的两个索引与两列上的一个composite index不同。查询每个表只能使用一个索引 *

pattern(code, section)pattern(section, code)上添加索引(需要使用实际数据进行实时测试,以找出哪一项提供了更好的结果)。


* very rare cases

除外