简体   繁体   English

MySql 在执行查询之前是否分析/优化查询?

[英]Does MySql analyze / optimize queries before executing them?

If you'd write a query like so:如果您要编写这样的查询:

SELECT * FROM `posts` WHERE `views` > 200 OR `views` > 100

Would MySql analyze that query and realize that it's actually equivalent to this? MySql 会分析该查询并意识到它实际上等同于这个吗?

SELECT * FROM `posts` WHERE `views` > 100

In other words, would MySql optimize the query such that it skips any unnecessary WHERE checks?换句话说,MySql 会优化查询以跳过任何不必要的WHERE检查吗?

I'm asking because I'm working on a piece of code that, for now, generates queries with redundant WHERE clauses.我之所以问,是因为我正在编写一段代码,该代码目前会生成带有冗余WHERE子句的查询。 I'm wondering if I should optimize those queries before I send them to MySql, or if that's unnecessary, because MySql would do it anyway.我想知道在将它们发送到 MySql之前是否应该优化这些查询,或者是否没有必要,因为 MySql 无论如何都会这样做。

Yes.是的。 MySQL does optimize queries before running them. MySQL 在运行查询之前会对其进行优化。 In fact, what runs has no obvious relationship to the SQL statement itself -- it is a directed acyclic graph .实际上,什么运行与 SQL 语句本身没有明显的关系——它是一个有向无环图

In the process, MySQL determines what indexes to use for the query, what join algorithms, sorts lists of constants in in lists, and much more.在此过程中,MySQL 确定用于查询的索引、连接算法、对列表中in常量列表进行排序等等。 The subject of optimizations is too long for Stack Overflow answer.对于 Stack Overflow 的答案来说,优化的主题太长了。

The optimizer also does some simplifications of the query.优化器还对查询进行了一些简化。 I'm not sure if those simplifications extend to inequalities.我不确定这些简化是否延伸到不平等。 However, there is little overhead in making the comparison twice.但是,进行两次比较几乎没有开销。

EXPLAIN SELECT... Shows how the query was rewritten -- but it still has the OR. EXPLAIN SELECT...显示查询是如何重写的——但它仍然有 OR。

The "Optimizer trace" says the same thing. “优化器跟踪”也说了同样的话。 However, when it gets into discussing the "cost", it gets smart and merges the two comparisons.但是,当它开始讨论“成本”时,它会变得聪明并合并两个比较。 (This is the case at least as far back as 5.6.) (这种情况至少可以追溯到 5.6。)

In many cases, OR should be avoided like covid.在许多情况下,应该像 covid 一样避免使用OR

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

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