SELECT * FROM msgs WHERE thread_id = ? LIMIT 100000, 100;
百萬資料表中,OFFSET 10 萬需掃描前 10 萬行再丟棄,MySQL 耗時 5 秒以上,且隨頁碼增長線性惡化 (O(n²))。
"A cursor is an opaque deletion-tolerant index into a B-tree keyed by source userid and modification time. It brings you to a point in time in the reverse chron sorted list." — John Kalucki, Twitter 架構師
-- 第一頁
SELECT * FROM msgs WHERE thread_id = ? ORDER BY id DESC LIMIT 100;
-- 回傳最後一筆 id 作為 next_cursor (例如 987654)
-- 下一頁
SELECT * FROM msgs WHERE thread_id = ? AND id < 987654 ORDER BY id DESC LIMIT 100;
ORDER BY created_at DESC, id DESC。| 分頁方式 | 第 1 頁 | 第 1000 頁 | 第 10000 頁 |
|---|---|---|---|
| OFFSET | 5 ms | 2.1 s | 22 s |
| Cursor (id < ?) | 4 ms | 5 ms | 6 ms |
Cursor 方式實現「常數時間」翻頁,是大資料集分頁的標準解法。