Why does MYSQL higher LIMIT offset slow the query down?

后端 未结 6 1241
忘掉有多难
忘掉有多难 2020-11-22 07:20

Scenario in short: A table with more than 16 million records [2GB in size]. The higher LIMIT offset with SELECT, the slower the query becomes, when using ORDER BY *prima

6条回答
  •  面向向阳花
    2020-11-22 08:11

    It's normal that higher offsets slow the query down, since the query needs to count off the first OFFSET + LIMIT records (and take only LIMIT of them). The higher is this value, the longer the query runs.

    The query cannot go right to OFFSET because, first, the records can be of different length, and, second, there can be gaps from deleted records. It needs to check and count each record on its way.

    Assuming that id is a PRIMARY KEY of a MyISAM table, you can speed it up by using this trick:

    SELECT  t.*
    FROM    (
            SELECT  id
            FROM    mytable
            ORDER BY
                    id
            LIMIT 10000, 30
            ) q
    JOIN    mytable t
    ON      t.id = q.id
    

    See this article:

    • MySQL ORDER BY / LIMIT performance: late row lookups

提交回复
热议问题