使用临时,在mysql中使用filesort一个坏主意?

she*_*ill 7 mysql

我正在尝试优化我的mysql查询,以避免'使用临时,使用filesort'.我可以使用一些帮助.第一; 这是解释

这是查询

select pf.*,m.login,m.avatar 
from profile_friends pf, members m  
where pf.friend_id = m.id and pf.member_id = 16586 
order by m.lastLogin desc 
limit 0,24;


mysql> EXPLAIN select pf.*,m.login,m.avatar from profile_friends pf, members m  where pf.friend_id = m.id and pf.member_id = 16586 order by m.lastLogin desc limit 0,24;
+----+-------------+-------+--------+-----------------------------------------------------+-----------------+---------+--------------------------+------+----------------------------------------------+
| id | select_type | table | type   | possible_keys                                       | key             | key_len | ref                      | rows | Extra                                        |
+----+-------------+-------+--------+-----------------------------------------------------+-----------------+---------+--------------------------+------+----------------------------------------------+
|  1 | SIMPLE      | pf    | ref    | member_id_index,friend_id_index                     | member_id_index |       4 | const                    |  160 | Using where; Using temporary; Using filesort |
|  1 | SIMPLE      | m     | eq_ref | PRIMARY,member_id_privacy_index,id_last_login_index | PRIMARY         |       4 | mydb.pf.friend_id        |    1 | Using where                                  |
Run Code Online (Sandbox Code Playgroud)

涉及2个表.ProfileFriends(pf)和Members(m).此查询只是试图找到此特定成员ID的"最近"24位朋友.最近表示按LastLogin日期排序.

谢谢

Cha*_*les 17

这是一个问题吗?是啊.

当你处理160行时,这是一个问题吗?不.

"Filesort"是一种方法,而不是实际创建文件并对其进行排序.如果我们谈论的是160,000行而不是160行,那么可能有理由考虑进一步的优化.

编辑:此外,您省略了实际的查询运行时间.你正在点击索引,只能处理少量行.如果这个查询占用的时间超过一小部分,那么甚至可能不值得进行优化.

  • +1是的,对于160行,MySQL甚至可以将临时表保存在内存中,而不将其写入磁盘."Filesort"有点误导,它只是意味着它的排序没有索引的好处. (3认同)