简体   繁体   English

为什么“解释”命令在同一 SQL 语句上产生不同的结果?

[英]Why 'explain' command yields different results on same SQL statement?

I migrated a MySQL database from one environment to another, and discovered that after migrating, a particular query runs extremely slower than it was.我将 MySQL 数据库从一个环境迁移到另一个环境,并发现迁移后,特定查询的运行速度比原来慢得多。

I was investigating the statement with 'explain' keyword (below) and found that the 'explain' command gives different output, on different servers.我正在调查带有 'explain' 关键字的语句(如下),发现 'explain' 命令在不同的服务器上给出了不同的输出。

explain select distinct j.job,f.path,p.path  
from fixes f
join  jobs j on  f.job=j.id 
join  paths p  on p.id =f.path  
where p.path like '//depot1/Dev\-trunk/%' ;

For the original one, it gives:对于原始的,它给出:

    1   SIMPLE  p   range   PRIMARY,path    path    752     **19**  Using where; Using index; Using temporary
    1   SIMPLE  f   ref path,job    path    8   p.p.id  **6448356** 
    1   SIMPLE  j   eq_ref  PRIMARY PRIMARY 8   p.f.job **1**   

And the same statement yields different output on the new environment:同样的语句在新环境中产生不同的输出:

    1   SIMPLE  j   index   PRIMARY job 62      **68486**   Using index; Using temporary
    1   SIMPLE  f   ref path,job    job 8   p.j.id  **812** 
    1   SIMPLE  p   eq_ref  PRIMARY,path    PRIMARY 8   p.f.path    **1**   Using where

FYI, it turns out that when migrating the database, there are some stats used for the engine optimizer to decide the best strategy to eg join tables, that apparently was not copied.仅供参考,事实证明,在迁移数据库时,引擎优化器使用了一些统计信息来决定最佳策略,例如连接表,显然没有复制。

The solution is to run ANALYZE on each of the tables to 'rebuild' such information.解决方案是在每个表上运行ANALYZE以“重建”此类信息。 So after doing the ANALYZE to each of the table, and run the explain command again, the output agrees and the query speed increases dramatically.所以在对每张表做ANALYZE后,再次运行explain命令,输出一致,查询速度大幅提升。

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

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