I have a simple SELECT * From tv Where Client = 'ABCD'
query and when I do an EXPLAIN EXTENDED
, it gives me two different results. When executing the query, one of them take a few milliseconds, while the other takes about 3 seconds. Why would it give two different explain results and what is causing the slowness?
Slow Query:
Fast Query:
Q Why does the same exact query produce 2 different MySQL explain results?
A Because something is different. If not in the query, then between the two tables, or database instances.
All of these should be reviewed, to find the difference:
- Are they running on the same version of MySQL (
SHOW VARIABLES LIKE '%version%'
) - Are the instances running the same characterset (
SHOW [GLOBAL] VARIABLES LIKE 'character_set%'
) - Are the table columns using the same characterset (
SHOW CREATE TABLE
) - Are both tables using the same storage engine? (
SHOW CREATE TABLE
) - If the primary key is a composite key, are the columns in the same order (
SHOW CREATE TABLE
) - Are statistics up to date and accurate?
- Is one of the tables fragmented, due to a lot of insert,update,delete activity?
- Is the MyISAM key cache or the InnoDB buffers the same size on both servers?
I solved by updating table statistics.
On MySQL i did:
OPTIMIZE TABLE [tablename]
Well the estimated number of row are also different.
So MySQL uses table statistics to determine which indexes to us and how to use them. Since the tables appears to have a different amount of rows in it it is only reasonable that the query plans would differ as the statistics will be different.
Update:
I did not read the row column correctly. Thus I assumed there is a huge difference in rows. This is not the case. Seems like the statistics might be out of date on the table with the slow query. Please run a OPTIMIZE TABLE statement on the slow query table. This will essentially rebuild the table.
the slow query shows the type as ref
while the fast query shows the type as range
. I suspect that you are missing an index on your Client row on the slow table.
I can confirm this kind of behavior. Just spent whole day to get it. Sometimes, when you are not using statements PRIMARY = PRIMARY (eg. using just part of the composite primary key), Mysql (resp. MariaDB) is executing MUCH faster queries on DB with a lot of data (production DB), instead of DB with just sample data (production env.)
My solution was to copy part of prod. data to dev database - it made some queries executed with different strategy, and of course, faster.
来源:https://stackoverflow.com/questions/18218071/why-does-the-same-exact-query-produce-2-different-mysql-explain-results