如何优化mysql查询

时间:2019-03-14 21:31:22

标签: mysql sql performance mysql-slow-query-log

我在使用mysql查询时遇到问题,有时需要超过80秒才能执行。

您能帮我优化它吗?

这是我的SQL代码

SELECT
 codFinAtl,
 nome,
 cognome,
 dataNascita AS annoNascita,
 MIN(tempoRisultato) AS tempoRisultato
FROM
graduatorie
INNER JOIN anagrafica ON codFin = codFinAtl
INNER JOIN manifestazionigrad ON manifestazionigrad.codice = graduatorie.codMan
WHERE
 anagrafica.eliminato = 'n' 
 AND graduatorie.eliminato = 'n' 
 AND codGara IN('01', '81') 
 AND sesso = 'F' 
 AND manifestazionigrad.aa = '2018/19' 
 AND graduatorie.baseVasca = '25' 
 AND tempoRisultato IS NOT NULL 
 AND dataNascita BETWEEN '20050101' AND '20061231'
GROUP BY
 codFinAtl
ORDER BY
 tempoRisultato,
 cognome,
 nome

和我的数据库模式 enter image description here

[更新]

这里有EXPLAIN查询的结果

+----+-------------+--------------------+------------+--------+--------------------------+-----------+---------+-------------------------------+--------+----------+----------------------------------------------+
| id | select_type | table              | partitions | type   | possible_keys            | key       | key_len | ref                           | rows   | filtered | Extra                                        |
+----+-------------+--------------------+------------+--------+--------------------------+-----------+---------+-------------------------------+--------+----------+----------------------------------------------+
|  1 | SIMPLE      | anagrafica         | NULL       | ALL    | codFin                   | NULL      | NULL    | NULL                          | 334094 |     0.11 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | graduatorie        | NULL       | ref    | codMan,codFinAtl,codGara | codFinAtl | 33      | finsicilia.anagrafica.codFin  |     20 |     0.24 | Using where                                  |
|  1 | SIMPLE      | manifestazionigrad | NULL       | eq_ref | codice                   | codice    | 32      | finsicilia.graduatorie.codMan |      1 |    10.00 | Using index condition; Using where           |
+----+-------------+--------------------+------------+--------+--------------------------+-----------+---------+-------------------------------+--------+----------+----------------------------------------------+

1 个答案:

答案 0 :(得分:0)

graduatorie:  INDEX(eliminato, baseVasca)
manifestazionigrad:  INDEX(aa, codMan)

这些可能还不够。请限定查询中的每一列,以便我们知道它们来自哪个表。

但是真正的问题可能是“爆炸爆炸”。首先,它由JOINing爆炸,然后由GROUP BY爆炸。

是否可以在没有任何MIN(tempoRisultato)的情况下计算JOINs ? (我什至不知道涉及哪个表。)如果有,请提供,然后我们可以讨论下一步要做什么。可能有两种选择:带有MIN的派生表,或JOIN中的子查询,它们可能是相关的或不相关的。

({tempoRisultato似乎在两个表中!)