了解MySQL中EXPLAIN的结果

时间:2016-05-23 11:50:01

标签: mysql sql query-performance explain

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

查询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之外,所有列都相同。那么哪一个更好:

    • SIMPLESIMPLE
    • PRIMARYDEPENDENT SUBQUERY
    • Using whereUsing where; Using join buffer (Block Nested Loop)
    • Using whereUsing where
  1. 编辑:以下是这两个查询:

    查询1:

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

    QUERY2:

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

1 个答案:

答案 0 :(得分:0)

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

使用数据库的第1步是了解密钥(索引)。

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

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

A quick lesson on building indexes

了解EXPLAIN需要建立索引基础。现在讨论EXPLAIN所说的内容还为时过早。