且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用变量时的慢SQL语句

更新时间:2023-02-06 22:26:40

问题是查询优化器在使用变量时找不到合适的索引时做得不好.这是一个已知问题.

The problem is that the query optimizer does a bad job on finding a suitable index when using variables. This is a known issue.

如果在两个查询上都使用EXPLAIN,则会看到不同之处.只是在不必要时尽量避免使用变量.

If you use EXPLAIN on both queries, you will see the difference. Just try to avoid variables when not necessary.

对于第一个查询,优化器查看"所选值并确定可以完美地使用索引来更有效地满足所选范围.

For the first query, the optimizer "sees" the chosen values and decides an index can be perfectly used to satisfy the selected range more efficiently.

对于第二个查询,优化器不知道定义范围的两个值,而是决定退回到完全扫描.

For the second query, the optimizer is unaware of the two values that define the range, and decides to fall back to a FULL SCAN instead.