8.8.1 Optimizing Queries with EXPLAIN使用EXPLAIN优化查询

The EXPLAIN statement provides information about how MySQL executes statements:EXPLAIN语句提供有关MySQL如何执行语句的信息:

With the help of EXPLAIN, you can see where you should add indexes to tables so that the statement executes faster by using indexes to find rows. EXPLAIN的帮助下,您可以看到应该在哪里向表添加索引,以便通过使用索引查找行,语句执行得更快。You can also use EXPLAIN to check whether the optimizer joins the tables in an optimal order. 还可以使用EXPLAIN检查优化器是否以最佳顺序连接表。To give a hint to the optimizer to use a join order corresponding to the order in which the tables are named in a SELECT statement, begin the statement with SELECT STRAIGHT_JOIN rather than just SELECT. 要提示优化器使用与SELECT语句中表的命名顺序相对应的联接顺序,请在语句开头使用SELECT STRAIGHT_JOIN,而不仅仅是SELECT(See Section 13.2.10, “SELECT Statement”.) (请参阅第13.2.10节,“SELECT语句”。)However, STRAIGHT_JOIN may prevent indexes from being used because it disables semijoin transformations. 但是,STRAIGHT_JOIN可能会阻止使用索引,因为它禁用半连接转换。See Section 8.2.2.1, “Optimizing IN and EXISTS Subquery Predicates with Semijoin Transformations”.请参阅第8.2.2.1节,“使用半联接转换优化IN和EXISTS子查询谓词”

The optimizer trace may sometimes provide information complementary to that of EXPLAIN. 优化器跟踪有时可以提供与EXPLAIN补充的信息。However, the optimizer trace format and content are subject to change between versions. 但是,优化器跟踪格式和内容在版本之间可能会发生更改。For details, see MySQL Internals: Tracing the Optimizer.有关详细信息,请参阅MySQL内部:跟踪优化器

If you have a problem with indexes not being used when you believe that they should be, run ANALYZE TABLE to update table statistics, such as cardinality of keys, that can affect the choices the optimizer makes. 如果在您认为应该使用索引时,索引没有被使用,那么运行ANALYZE TABLE来更新表统计信息,例如键的基数,这可能会影响优化器所做的选择。See Section 13.7.3.1, “ANALYZE TABLE Statement”.请参阅第13.7.3.1节,“ANALYZE TABLE语句”

Note注意

EXPLAIN can also be used to obtain information about the columns in a table. EXPLAIN还可用于获取有关表中列的信息。EXPLAIN tbl_name is synonymous with DESCRIBE tbl_name and SHOW COLUMNS FROM tbl_name. EXPLAIN tbl_nameDESCRIBE tbl_name以及SHOW COLUMNS FROM tbl_name同义。For more information, see Section 13.8.1, “DESCRIBE Statement”, and Section 13.7.7.5, “SHOW COLUMNS Statement”.有关更多信息,请参阅第13.8.1节,“DESCRIBE语句”第13.7.7.5节,“SHOW COLUMNS语句”