首页 > 解决方案 > MySQL查询索引

问题描述

我正在使用 MySQL 5.6 并尝试优化下一个查询:

SELECT t1.field1,
       ...
       t1.field30,
       t2.field1
FROM Table1 t1
         JOIN Table2 t2 ON t1.fk_int = t2.pk_int
WHERE t1.int_field = ?
  AND t1.enum_filed != 'value'
ORDER BY t1.created_datetime desc;

一个响应可以包含数百万条记录,每行包含 31 列。

现在 EXPLAIN 在 Extra 中说计划者使用“使用位置”。

我尝试添加下一个索引:

create index test_idx ON Table1 (int_field, enum_filed, created_datetime, fk_int);

在那之后,EXPLAIN 在 Extra 中说计划器使用“使用索引条件;使用文件排序”

带有索引的 EXPLAIN 中的“行”值小于没有它的值。但在实践中执行时间较长。

所以,接下来的问题是:

  1. 这个查询的最佳索引是什么?
  2. 为什么EXPLAIN说索引查询的'key_len'是5。不应该是4+1+8+4=17吗?
  3. ORDER BY 中的字段是否应该在索引中?
  4. JOIN 中的字段是否应该在索引中?

标签: mysqlsqlindexingquery-optimization

解决方案


尝试以这种方式重构您的索引,
避免(o 在 fk_int 之后向右移动) created_datetime 列.. 并将 fk_int 移动到 enum_filed 列之前.. 在这种情况下,用于过滤器的另外 3 个列应该更好地使用)

create index test_idx ON Table1 (int_field, fk_int, enum_filed);

确保您在 table2 列 pk_int 上也有特定索引。如果你还没有添加

create index test_idx ON Table2 (int_field, fk_int, enum_filed);

推荐阅读