繁体   English   中英

优化非常慢的Mysql查询

[英]Optimize very slow Mysql Query

我需要帮助优化此查询:

SELECT 
    c.rut, c.nombre, c.apellido, c.estado, c.porcentajeavance,  
    c.porcentajenota, c.nota, c.curso, c.fecha_inicio,   
    c.fecha_termino, c.grupo, c.fecha, c.cargo
FROM tbl_historico c
WHERE fecha = ( 
    SELECT max( t.fecha ) fecha
    FROM tbl_historico t
    WHERE t.rut = c.rut AND c.curso = t.curso 
)

解释输出:

+----+--------------------+-------+------+-----------------+-------+---------+-----------------------------------------+--------+-------------+
| id | select_type        | table | type | possible_keys   | key   | key_len | ref                                     | rows   | Extra       |
+----+--------------------+-------+------+-----------------+-------+---------+-----------------------------------------+--------+-------------+
|  1 | PRIMARY            | c     | ALL  | NULL            | NULL  | NULL    | NULL                                    | 158008 | Using where |
|  2 | DEPENDENT SUBQUERY | t     | ref  | rut,rut_2,rut_3 | rut_3 | 514     | campus_mdle1.c.rut,campus_mdle1.c.curso |     27 | Using index |
+----+--------------------+-------+------+-----------------+-------+---------+-----------------------------------------+--------+-------------+

我认为你可以重写它以避免相关的子查询:

SELECT c.rut, c.nombre, c.apellido, c.estado, c.porcentajeavance
     , c.porcentajenota, c.nota, c.curso, c.fecha_inicio
     , c.fecha_termino, c.grupo, c.fecha, c.cargo
FROM 
      tbl_historico AS c
  JOIN
      ( SELECT rut, curso, MAX(fetcha) AS fetcha
        FROM tbl_historico 
        GROUP BY rut, curso 
      ) AS grp
    ON (grp.rut, grp.curso, grp.fetcha)
     = ( c.rut,   c.curso,   c.fetcha)

(rut, curso, fetcha)上的索引对此查询很有用。


另一种解决方案是:

SELECT c.rut, c.nombre, c.apellido, c.estado, c.porcentajeavance
     , c.porcentajenota, c.nota, c.curso, c.fecha_inicio
     , c.fecha_termino, c.grupo, c.fecha, c.cargo
FROM 
      ( SELECT rut, curso
        FROM tbl_historico
        GROUP BY rut, curso
        ORDER BY rut, curso                --- custom order and
        LIMIT 30 OFFSET 0                  --- limit here
      ) AS dc
  JOIN
      tbl_historico AS c
    ON c.PK =                              --- the Primary Key of the table here
       ( SELECT h.PK                       --- and here
         FROM tbl_historico AS h
         WHERE (h.rut, h.curso) = (dc.rut, dc.curso)
         ORDER BY h.fetcha DESC
         LIMIT 1  
       ) 

这将显示不同的结果(在绑定的情况下,将仅显示其中一个绑定的行)但如果要限制行数,则可能更快。

SELECT c.rut, c.nombre, c.apellido,c.estado, c.porcentajeavance,  
       c.porcentajenota, c.nota, c.curso, c.fecha_inicio, c.fecha_termino,c.grupo,c.fecha,c.cargo
FROM tbl_historico c
ORDER BY c.fecha DESC
LIMIT 1

暂无
暂无

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

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