我有一个带有嵌套连接的 SQL 查询:
SELECT rh.host, rh.report, COUNT(results.id), COUNT(results_2.id), COUNT(results_3.id), COUNT(results_4.id)
FROM report_hosts rh
INNER JOIN report_results rr ON rh.report = rr.report
LEFT OUTER JOIN results ON rr.result = results.id AND results.type = 'Hole' AND results.host = rh.host
LEFT OUTER JOIN results results_2 ON rr.result = results_2.id AND results_2.type = 'Warning' AND results_2.host = rh.host
LEFT OUTER JOIN results results_3 ON rr.result = results_3.id AND results_3.type = 'Note' AND results_3.host = rh.host
LEFT OUTER JOIN results results_4 ON rr.result = results_4.id AND results_4.type = 'Log' AND results_4.host = rh.host
GROUP BY rh.host
原样查询大约需要 5 秒,其中 99.7%复制到临时表。一个EXPLAIN
完整的查询显示为:
+----+-------------+-----------+--------+---------------+---------+---------+-------------------+------+---------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+--------+---------------+---------+---------+-------------------+------+---------------------------------+
| 1 | SIMPLE | rr | ALL | report | NULL | NULL | NULL | 3139 | Using temporary; Using filesort |
| 1 | SIMPLE | rh | ref | report | report | 5 | openvas.rr.report | 167 | Using where |
| 1 | SIMPLE | results | eq_ref | PRIMARY,type | PRIMARY | 4 | openvas.rr.result | 1 | |
| 1 | SIMPLE | results_2 | eq_ref | PRIMARY,type | PRIMARY | 4 | openvas.rr.result | 1 | |
| 1 | SIMPLE | results_3 | eq_ref | PRIMARY,type | PRIMARY | 4 | openvas.rr.result | 1 | |
| 1 | SIMPLE | results_4 | eq_ref | PRIMARY,type | PRIMARY | 4 | openvas.rr.result | 1 | |
+----+-------------+-----------+--------+---------------+---------+---------+-------------------+------+---------------------------------+
当我删除LEFT JOIN
s 时,查询会在大约 1 秒内执行,每个LEFT JOIN
会增加大约一秒的执行时间。
我的问题:
谁能解释一下,如果有更多的 s,为什么一个连接的复制到临时表LEFT JOIN
任务需要更长的时间?MySQL 是否为每个 JOIN 多次复制临时表?
我怎样才能避免这种情况?我错过了索引吗?
我打算完成的工作: 我有一个包含几台主机扫描结果的表。每个结果都按类型分类(“孔”、“警告”、“注释”或“日志”)。我想选择每个主机和相应数量的漏洞、警告、注释和日志。作为“限制”,我有一个事实,即并非每个主机都有每种类型的结果。