简体   繁体   English

优化MySQL查询(慢)

[英]Optimize MySQL Query (Slow)

Someone can help me to optimize the following MySQL query? 有人可以帮助我优化以下MySQL查询吗?

SELECT SUM(ROUND(rp.distance,2)), t.name, MONTH(tr.assigned)
FROM tab1 tr
JOIN tab2 rp ON rp.robot=tr.robot 
JOIN tab3 t ON t.idTask=tr.idTask
GROUP BY t.name, MONTH(tr.assigned)

The query takes 20 seconds to execute. 查询需要20秒才能执行。 Without the GROUP BY down to 10 seconds. 没有GROUP BY的话,最多10秒。 I tested with DISTINCT but I failed to improve the time. 我在DISTINCT上进行了测试,但未能改善时间。 Any ideas? 有任何想法吗?

try this query 试试这个查询

SELECT SUM(distance), t.name, MONTH(tr.assigned)
FROM tab1 tr
JOIN tab2 rp ON rp.robot=tr.robot 
JOIN (select ROUND(rp.distance,2) as distance, a.idTask from tab3 a) t ON t.idTask=tr.idTask
GROUP BY t.name, MONTH(tr.assigned)

This is your query: 这是您的查询:

SELECT SUM(ROUND(rp.distance, 2)), t.name, MONTH(tr.assigned)
FROM tab1 tr JOIN
     tab2 rp
     ON rp.robot = tr.robot JOIN
     tab3 t
     ON t.idTask = tr.idTask
GROUP BY t.name, MONTH(tr.assigned);

It looks reasonable. 看起来很合理。 So, before radically rewriting it, do you have the following indexes: tab1(robot, idtask, assigned) , tbl2(robot) , and tab3(idtask, name) . 因此,在彻底重写之前,您是否具有以下索引: tab1(robot, idtask, assigned)tbl2(robot)tab3(idtask, name)

Next, perhaps the volume of data is just too big. 接下来,也许数据量太大。 MySQL is pretty bad when it comes to group by -- and 10 seconds for a group by suggests a lot of data. MySQL是非常糟糕的,当涉及到group by - 10秒一group by提出大量的数据。 Is there any way you can reduce the size of the data? 有什么方法可以减少数据大小? What are the sizes of the tables? 桌子的大小是多少? How large is the result set? 结果集有多大?

If you have lots of data, then 20 seconds may not be unreasonable. 如果您有大量数据,那么20秒可能并不合理。

Looks like you are grouping by string, so you need to add index on name column. 看起来您正在按字符串分组,因此您需要在name列上添加索引。 You have to always use indexes when joining MySQL tables 加入MySQL表时必须始终使用索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM