Heim >Datenbank >MySQL-Tutorial >辛星简译MySQL中的last_query_cost_MySQL
我们都知道在MySQL中可以通过show status like 'last_query_cost' 来查看查上一个查询的代价,而且它是io_cost和cpu_cost的开销总和,它通常也是我们评价一个查询的执行效率的一个常用指标。
下面是一段英文解释:
The total cost of the last compiled query as computed by the query optimizer. This is useful for comparing the cost of different query plans for the same query. The default value of 0 means that no query has been compiled yet. The default value is 0. Last_query_cost has session scope.
The Last_query_cost value can be computed accurately only for simple “flat” queries, not complex queries such as those with subqueries or UNION. For the latter, the value is set to 0.
Q:
When doing query optimization, the SHOW STATUS query returns values that are easy to understand with some practice and explanation.
But last_query_cost is obscure and poorly documented.
The only thing explained is that it must be read as an anti-macho value: the smaller the better.
But do we have further information about this high-level value? What is its unit? How is it calculated (estimated)? etc. How can we use it for an advanced profiling?
A:
This has to do with how the MySQL Query Optimizer works. When you enter and execute a query, MySQL will construct a query plan. This is done by evaluating how the query can be executed in several different ways, and assigning "costs" to the different possibilities. These costs are based mostly on internal statistics, and includes data such as the number of rows in the table, the cardinality of different indices and so forth. When this is done, MySQL choses the least expensive plan and executes the query. The last_query_cost value is this cost value.
As you've no doubt seen in the manual:
The total cost of the last compiled query as computed by the query optimizer. This is useful for comparing the cost of different query plans for the same query. The default value of 0 means that no query has been compiled yet. The default value is 0. Last_query_cost has session scope.
This is indeed true. The value is only useful as a quantitative measurement to compare different queries.
相信朋友们只要英语过了六级,甚至是四级都能看得懂,因此我这里只是提炼一下其中的要点,要点如下:
(1)它是作为比较各个查询之间的开销的一个依据。
(2)它只能检测比较简单的查询开销,对于包含子查询和union的查询是测试不出来的。
(3)当我们执行查询的时候,MySQL会自动生成一个执行计划,也就是query plan,而且通常有很多种不同的实现方式,它会选择最低的那一个,而这个cost值就是开销最低的那一个。
(4)它对于比较我们的开销是非常有用的,特别是我们有好几种查询方式可选的时候。