问题
I migrated a MySQL database from one environment to another, and discovered that after migrating, a particular query runs extremely slower than it was.
I was investigating the statement with 'explain' keyword (below) and found that the 'explain' command gives different output, on different servers.
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
回答1:
FYI, it turns out that when migrating the database, there are some stats used for the engine optimizer to decide the best strategy to e.g. join tables, that apparently was not copied.
The solution is to run ANALYZE
on each of the tables to 'rebuild' such information. 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.
来源:https://stackoverflow.com/questions/13390729/mysql-why-explain-command-yields-different-results-on-same-sql-statement