Avoid filesort with INNER JOIN + ORDER BY

邮差的信 提交于 2019-12-01 05:58:58

You can help MySQL optimizer by moving all the filtering work to a subquery what accesses only indices (manipulating indices is usually much faster than manipulating other data), and fetching rest of the data in the outermost query:

SELECT posts.post_id,
       posts.post_b_id,
       posts.post_title,
       posts.post_cont,
       posts.thumb,
       posts.post_user,
       boards.board_title_l,
       boards.board_title
FROM   (SELECT post_id
        FROM   posts
               JOIN follow
                 ON posts.post_b_id = follow.board_id
        WHERE  follow.user_id = 1
        ORDER  BY post_id DESC
        LIMIT  10) sq
       JOIN posts
         ON posts.post_id = sq.post_id
       JOIN boards
         ON boards.board_id = posts.post_b_id

Note that I omit ORDER BY posts.post_id DESC from the outer query, because it is usually faster to sort the final result in your code rather than sorting using a MySQL query (MySQL often uses filesort for that).

P.S. You can replace the unique key in the follow table with a primary key.

Increasing the sort_buffer_size parameter will increase the amount of memory MySQL uses before resorting to a temporary disk file and should help considerably.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!