Avoid filesort with INNER JOIN + ORDER BY

前端 未结 2 1948
野的像风
野的像风 2021-01-13 05:50

I\'ve been reading other posts but I didn\'t managed to fix my query.

Using DESC order the query is x20 times slower, I must improve that. This is the q

相关标签:
2条回答
  • 2021-01-13 06:22

    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.

    0 讨论(0)
  • 2021-01-13 06:30

    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.

    0 讨论(0)
提交回复
热议问题