简体   繁体   English

MySQL为什么不优化此简单查询并提供缓存结果?

[英]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. 当我在MySQL提示符下执行此查询时,花了大约0.90秒来提供表中的行数。 When I repeated the same query, I got the result in 0.00 seconds , consistently . 当我重复相同的查询时,始终0.00秒内得到结果。 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. 现在,我将条件更改为where (1=1) ,执行时间0.65秒 When I repeated this new query, I got the result in 0.00 seconds , consistently . 当我重复此新查询时,始终0.00秒内得到结果。 This again implies that the result was cached against this new query. 这再次表明结果是针对此新查询缓存的。

The where clause is unnecessary, and can be removed. where子句是不必要的,可以删除。 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. 如果将结果针对此优化查询进行缓存,则即使我where (N=N)更改N,也只有第一次执行应该花费更多的时间,并且每次重复都应该在0.00秒内得到结果。没有对此进行优化。

Does MySQL optimise such queries ? MySQL是否优化此类查询? 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. 我在CentOS 5.2上使用的是MySQL 5.0.77,它可能很旧,并且这个问题在较新的发行版中可能不存在,但我更想知道原因。

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 选择* FROM tbl_name
  • Select * from tbl_name 选择* 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. 使用不同数据库,不同协议版本或不同默认字符集的查询被视为不同查询,并分别进行缓存。

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

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