mysql - 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 中的“行”值小于没有它的值。但在实践中执行时间较长。
所以,接下来的问题是:
- 这个查询的最佳索引是什么?
- 为什么EXPLAIN说索引查询的'key_len'是5。不应该是4+1+8+4=17吗?
- ORDER BY 中的字段是否应该在索引中?
- JOIN 中的字段是否应该在索引中?
解决方案
尝试以这种方式重构您的索引,
避免(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);
推荐阅读
- javascript - eventstream zip 和 Bacon.when 有什么区别
- javascript - 第一个加载页面上的 Javascript 函数
- c# - 删除部分 IL 语言条件
- c# - 带有任何类型回调的通配符泛型?
- r - 在 Rmarkdown 中的文本中包含空格的引用变量名称
- java - 如何使用android studio以编程方式记录android设备的所有入站和出站连接
- python - 根据行对列求和。例如,基于行 'male' 和 'female' 的 sum 列自杀_no
- pivot-table - Qlikview Pivot Table Top X 按周
- python - 当用户在模态窗口外单击时如何响铃?
- deep-learning - TensorFlow CNN 形状不匹配