1. 原语句:
  2. SELECT
  3. ifnull(system_name, "ALL") AS system_name,
  4. ifnull(DISK, 0) AS disk
  5. FROM
  6. (
  7. SELECT
  8. ROUND(SUM(disk_per) / COUNT(*), 4) AS DISK,
  9. s1.SYSTEM_ID
  10. FROM
  11. vm_info_tab p1
  12. LEFT JOIN (
  13. SELECT
  14. ROUND(
  15. (
  16. ifnull(SUM(disk_total), disk_free) - SUM(disk_free)
  17. ) / SUM(disk_total),
  18. 4
  19. ) * 100 AS disk_per,
  20. per_hid
  21. FROM
  22. x86.vm_performance_tab f1
  23. WHERE
  24. f1.Per_Time > TIMESTAMPADD(WEEK, - 1, NOW())
  25. GROUP BY
  26. per_hid
  27. ) AS perf_value ON p1.ip = perf_value.per_hid
  28. LEFT JOIN system_device_relation_tab s1 ON p1.vm_id = s1.DEVICE_ID
  29. GROUP BY s1.`SYSTEM_ID`
  30. ) p1
  31. LEFT JOIN system_info_tab p2 ON p1.system_id = p2.`system_id`;

+————-+——–+
| system_name | disk |
+————-+——–+
| ALL | 0.0000 |
+————-+——–+
1 row in set (6.30 sec)      <——— 0条记录使用了 6.30秒

 

1. 最大问题在于 join 后进行 group by ,  两表 join时候会有很多数据进行匹配 , group 有去重功能 , 可以先对数据进行去重 , 然后再进行join , 这样减少join数据时候比对量 , 并且用上了索引了 , 原语句只用了join 字段时候的索引 , 最后group by就要从表返回数据,这就是慢的原因之一 , 第3个操作就是用了 using where 过滤元组和是否读取数据文件或索引文件没有关系 , mysql官档:

Using where
A WHERE clause is used to restrict which rows to match against the next table or send to the client. Unless you specifically intend to fetch or examine all rows from the table, you may have something wrong in your query if the Extra value is not Using where and the table join type is ALL or index.

2. 分析后主要有2个表进行group by , f1 和 s1 表

  1. 修改后:
  2. SELECT
  3. ifnull( system_name, "ALL" ) AS system_name,
  4. ifnull( DISK, 0 ) AS disk
  5. FROM
  6. (
  7. SELECT
  8. ROUND( SUM( disk_per ) / COUNT( * ), 4 ) AS DISK,
  9. s1.SYSTEM_ID
  10. FROM
  11. vm_info_tab p1
  12. LEFT JOIN (
  13. SELECT
  14. ROUND( ( ifnull( SUM( disk_total ), disk_free ) - SUM( disk_free ) ) / SUM( disk_total ), 4 ) * 100 AS disk_per,
  15. per_hid
  16. FROM
  17. (
  18. SELECT
  19. disk_total,
  20. disk_free,
  21. per_hid
  22. FROM
  23. x86.vm_performance_tab f1
  24. INNER JOIN ( SELECT id FROM x86.vm_performance_tab f1 GROUP BY per_hid ) a ON f1.id = a.id
  25. WHERE
  26. f1.Per_Time > TIMESTAMPADD (
  27. WEEK, - 1,
  28. NOW ())
  29. ) f1
  30. GROUP BY
  31. f1.per_hid
  32. ) AS perf_value ON p1.ip = perf_value.per_hid
  33. LEFT JOIN system_device_relation_tab s1 ON p1.vm_id = s1.DEVICE_ID
  34. GROUP BY
  35. s1.` SYSTEM_ID `
  36. ) p1
  37. LEFT JOIN system_info_tab p2 ON p1.system_id = p2.` system_id `;

+————-+——–+
| system_name | disk |
+————-+——–+
| ALL | 0.0000 |
+————-+——–+
1 row in set (0.41 sec)      <——- 性能上来了

3. f1 字段使用 索引进行group by , 第5操作 , 提升了性能

 

版权声明:本文为kelvin19840813原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/kelvin19840813/p/10464308.html