理解 MySQL 中 EXPLAIN 的结果

Sha*_*deh 5 mysql sql explain query-performance

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

查询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) |
Run Code Online (Sandbox Code Playgroud)

查询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 |
Run Code Online (Sandbox Code Playgroud)

那么哪一个更好,为什么?

我读到EXPLAIN这里,但仍然不知道哪个参数重要?或者哪个参数告诉我这样的列需要索引,或者我的查询需要优化?

在上面这两个解释的结果中,所有列都是相同的,除了: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'
Run Code Online (Sandbox Code Playgroud)

查询2:

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

Ric*_*mes 1

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

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

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

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

关于构建索引的快速课程

学习EXPLAIN需要有索引基础。现在讨论这些内容还为时过早EXPLAIN