【问题标题】:Understanding the result of EXPLAIN in MySQL理解 MySQL 中 EXPLAIN 的结果
【发布时间】:2016-09-20 06:56:06
【问题描述】:

我有两个独立的查询,它们具有相同的输出。现在我想了解哪个更好?

查询1:

| id | select_type | table | type | possible_keys |    key | key_len |    ref | rows |                                              Extra |
|----|-------------|-------|------|---------------|--------|---------|--------|------|----------------------------------------------------|
|  1 |      SIMPLE |    t1 |  ALL |        (null) | (null) |  (null) | (null) |    9 |                                        Using where |
|  1 |      SIMPLE |    t2 |  ALL |        (null) | (null) |  (null) | (null) |    9 | Using where; Using join buffer (Block Nested Loop) |

查询2:

| id |        select_type | table | type | possible_keys |    key | key_len |    ref | rows |       Extra |
|----|--------------------|-------|------|---------------|--------|---------|--------|------|-------------|
|  1 |            PRIMARY |    t1 |  ALL |        (null) | (null) |  (null) | (null) |    9 | Using where |
|  2 | DEPENDENT SUBQUERY |    t2 |  ALL |        (null) | (null) |  (null) | (null) |    9 | Using where |

那么哪个更好,为什么?

我读到了EXPLAIN here,但我还是不知道哪个参数很重要?或者哪个参数告诉我这样一个列需要索引,或者我的查询需要优化?

在上面这两个解释的结果中,除了select_typeextra 之外,所有列都是相同的。那么哪个更好:

    • SIMPLE, SIMPLE
    • PRIMARY, DEPENDENT SUBQUERY
    • Using where, Using where; Using join buffer (Block Nested Loop)
    • Using where, Using where

编辑:这是这两个查询:

查询1:

SELECT t2.color FROM mytable t1
                JOIN mytable t2 ON t1.related = t2.id
                WHERE t1.id = '4'

查询2:

SELECT t1.color FROM mytable t1
    WHERE exists (select 1 from mytable t2
             where t1.id =  t2.related
               and t2.id ='4')

【问题讨论】:

  • 您能否向我们展示这两个查询,假设它们可以合理地适合问题?您的两个查询的当前运行时间是多少?
  • 创建一个大型测试数据集并运行两个查询器,看看哪个运行得更快。
  • @TimBiegeleisen 我已将这两个查询添加到我的问题中。
  • "或者哪个参数告诉我这样的列需要索引,或者我的查询需要优化?"解释中没有这样的列。如果解释告诉我们如何更改您的查询,那就太容易了。由您来解决这个问题,并解释是一个很好的工具来帮助解决这个问题。
  • @Shadow 是的,基准测试会有所帮助。但实际上我试图了解EXPLAIN 在这种情况下如何帮助我。

标签: mysql sql query-performance explain


【解决方案1】:

重要的是这个时间是possible keys: NULL。也就是说,您没有索引。由于该表只有大约 9 行,因此这不是性能问题。然而。该查询将达到大约 9*9 = 81 行。如果您的表达到 1000 行,则将命中 1000000 行以返回结果集。

使用数据库的第一步是了解键(索引)。

使用适当的索引,此查询应该涉及大约 2 行,无论表的大小。

您可能需要PRIMARY KEY(id)。如果您提供SHOW CREATE TABLE mytable,将会对我们有所帮助。

A quick lesson on building indexes

了解EXPLAIN 需要有索引基础。现在讨论EXPLAIN 在说什么还为时过早。

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 2016-03-11
    • 2015-08-19
    • 2011-12-06
    • 1970-01-01
    • 2014-01-27
    • 2020-04-04
    • 2012-12-17
    • 1970-01-01
    相关资源
    最近更新 更多