不久前我得到了一些有关特定查询的帮助。链接如下:SQL Group BY using strings in new columns
我的查询看起来与此类似:
SELECT event_data, class_40_winner, class_30_winner
FROM events e
LEFT JOIN (SELECT result_event, name AS class_40_winner
FROM results
WHERE class = 40 AND position = 1) c40 ON e.id = c40.result_event
LEFT JOIN (SELECT result_event, name AS class_30_winner
FROM results
WHERE class = 30 AND position = 1) c30 ON e.id = c30.result_event
我现在已在数据库中输入了足够的数据(22,000 行),该查询需要 6 秒多的时间才能完成。 (我的实际查询比上面的查询更大,因为它现在有 4 个连接。)
我在查询中使用了“解释”功能来查看。 “结果”表中的每个查询都拉入 22,000 行,因此这似乎是问题所在。
我已经做了一些研究,听起来我应该能够在“结果”表上索引相关列以帮助加快速度。但当我这样做时,它实际上将我的查询速度减慢到了大约 10 秒。
对于如何改进此查询有什么建议吗?
最佳答案
据我所知,您正在旋转数据,我认为使用 max(case ...) ... group by
在旋转数据方面具有良好的性能。
我可以建议您改用此查询:
select event_date
, max(case when r.class = 40 then name end) `Class 40 Winner`
, max(case when r.class = 30 then name end) `Class 30 Winner`
from events e
left join results r on e.event_id = r.result_event and r.position = 1
group by event_date;
关于MySQL 查询耗时超过 6 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647621/