简体   繁体   中英

Why does MySQL not optimise this simple query and provide the result from cache?

Query :

select count(a_column) from a_table where (0=0) ;

When I executed this query at the MySQL prompt, it took about 0.90 seconds to provide the number of rows in the table. When I repeated the same query, I got the result in 0.00 seconds , consistently . This implies that the result was cached against this query.

Now I changed the condition to where (1=1) , it took 0.65 seconds to execute. When I repeated this new query, I got the result in 0.00 seconds , consistently . This again implies that the result was cached against this new query.

The where clause is unnecessary, and can be removed. If the result was cached against this optimised query, then only the first execution should take more time , and every repeat should have got the results in 0.00 seconds, even when I change N in where (N=N) , but it seems that MySQL did not do this optimisation.

Does MySQL optimise such queries ? What is the explanation of my mini experiments ?

I am using MySQL 5.0.77 on CentOS 5.2, which might be old, and this issue might not exist in newer releases, but I am more interested in knowing the reasons.

This behavior is documented in the manual .

Quoting the manual:

Incoming queries are compared to those in the query cache before parsing, so the following two queries are regarded as different by the query cache:

  • SELECT * FROM tbl_name
  • Select * from tbl_name

Queries must be exactly the same (byte for byte) to be seen as identical. In addition, query strings that are identical may be treated as different for other reasons. Queries that use different databases, different protocol versions, or different default character sets are considered different queries and are cached separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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