求解 Mysql 查询产生的 filesort 优化

2014-09-26 11:27:05 +08:00
 CosWind
Mysql两张表联合查询INNER JOIN加上ORDER BY 产生的filesort有解否?
3528 次点击
所在节点    程序员
17 条回复
incompatible
2014-09-26 11:38:18 +08:00
join的字段和order by的字段加上索引
CosWind
2014-09-26 11:41:52 +08:00
@incompatible 有联合索引,而且是顺序的。不行诶
CosWind
2014-09-26 11:47:50 +08:00
@incompatible INNER JOIN的字段是联合索引的前缀索引
yangqi
2014-09-26 11:49:30 +08:00
order by的字段是什么类型的, 是否有索引

另外你explain看一下
CosWind
2014-09-26 11:50:58 +08:00
@yangqi ORDER BY的字段是DATE类型,有和WHERE的条件构成的联合索引
CosWind
2014-09-26 11:52:06 +08:00
@yangqi explain的结果Using where; Using index; Using temporary; Using filesort
incompatible
2014-09-26 11:52:45 +08:00
@CosWind 先去掉order by,单独执行join的部分试试,以便推断到底是join和order by里的哪一个导致了filesort
CosWind
2014-09-26 11:54:11 +08:00
@incompatible 单独没问题。
yangqi
2014-09-26 11:55:20 +08:00
@CosWind 能把explain贴出来不, 要看的不是这些
CosWind
2014-09-26 11:59:01 +08:00
CosWind
2014-09-26 11:59:25 +08:00
CosWind
2014-09-26 12:00:50 +08:00
@yangqi http://img.itc.cn/photo/oD1XjXvEUYf 这个,刚那个没截取全
incompatible
2014-09-26 12:01:12 +08:00
@CosWind 我做了一个测试 如果where条件中只命中了某字段的一行(比如column = ?),那么对“与该字段构成联合索引的后续列”做order by的话,可以命中索引。 如果where条件中命中了多行(比如用 column
in (?, ? ...) 的方式),order by时就会引起filesort
不知你是否是这种情况
CosWind
2014-09-26 12:02:09 +08:00
@incompatible yes,可以说差不多是这个意思。因为我的是INNER JOIN,命中的是很多行
CosWind
2014-09-26 12:05:30 +08:00
@incompatible IN的方式会产生subquery,我用INNER JOIN代替了。
yangqi
2014-09-26 12:07:46 +08:00
http://dev.mysql.com/doc/refman/5.5/en/order-by-optimization.html

这里是官方对于order by使用索引的解释, 估计你的是下面这种情况, 不能用索引

You are joining many tables, and the columns in the ORDER BY are not all from the first nonconstant table that is used to retrieve rows. (This is the first table in the EXPLAIN output that does not have a const join type.)
CosWind
2014-09-26 13:17:12 +08:00
@yangqi SOGA。非常感谢。难怪我google一直找不到答案。文档也看过了。。没看你这么仔细的说。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/135796

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX