MySQL uses a cost-based optimizer to determine the best way to resolve a query. In many cases, MySQL can calculate the best possible query plan, but sometimes MySQL does not have enough information about the data at hand and has to make “educated” guesses about the data.
当 MySQL 没有做出“正确”操作的情况下,你可以使用的工具来帮助 MySQL 有:For the cases when MySQL does not do the "right" thing, tools that you have available to help MySQL are:
使用
EXPLAIN语句获取有关 MySQL 如何处理查询的信息。要使用它,只需在你的SELECT语句前添加关键字EXPLAIN:Use theEXPLAINstatement to get information about how MySQL processes a query. To use it, just add the keywordEXPLAINto the front of yourSELECTstatement:mysql>
EXPLAIN SELECT * FROM t1, t2 WHERE t1.i = t2.i;EXPLAIN将在第 15.8.2 节,“EXPLAIN 语句”中有更详细的讨论。EXPLAINis discussed in more detail in Section 15.8.2, “EXPLAIN Statement”.使用
ANALYZE TABLE tbl_name来更新扫描表的键分布。参见 第 15.7.3.1 节,“ANALYZE TABLE 语句”。UseANALYZE TABLEto update the key distributions for the scanned table. See Section 15.7.3.1, “ANALYZE TABLE Statement”.tbl_name对扫描表使用
FORCE INDEX,告诉 MySQL 与使用给定索引相比,表扫描代价非常高: UseFORCE INDEXfor the scanned table to tell MySQL that table scans are very expensive compared to using the given index:SELECT * FROM t1, t2 FORCE INDEX (index_for_column) WHERE t1.col_name=t2.col_name;
USE INDEX和IGNORE INDEX也可能有用。参见 第 10.9.4 节,“索引提示”。USE INDEXandIGNORE INDEXmay also be useful. See Section 10.9.4, “Index Hints”.全局和表级
STRAIGHT_JOIN。参见 第 15.2.13 节,“SELECT 语句”。Global and table-levelSTRAIGHT_JOIN. See Section 15.2.13, “SELECT Statement”.您可以调整全局或线程特定的系统变量。例如,可以使用 mysqld 启动,并使用
--max-seeks-for-key=1000选项,或者使用SET max_seeks_for_key=1000来告诉优化器假设没有键扫描会导致超过 1000 次键查找。请参见 第 7.1.8 节,“服务器系统变量”。You can tune global or thread-specific system variables. For example, start mysqld with the--max-seeks-for-key=1000option or useSET max_seeks_for_key=1000to tell the optimizer to assume that no key scan causes more than 1,000 key seeks. See Section 7.1.8, “Server System Variables”.