Why does the same exact query produce 2 different MySQL explain results?

ぐ巨炮叔叔 提交于 2019-12-04 19:42:05

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!