SELECT * FROM posts ORDER BY id DESC LIMIT 20 OFFSET 1000000;
MySQL 必須掃描前 1,000,020 行再丟棄 1,000,000 行,**深分頁效能急劇下降**。
| 策略 | 原理 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|---|
| COUNT 快取 | 首頁查總數,後頁透過參數傳遞 | 簡單、相容現有邏輯 | 資料變動時總數不準 | 低頻寫入、首頁為主 |
| 延遲 COUNT | 先查 LIST,若 < 20 筆則不查 COUNT | 單頁結果免 COUNT | 多頁仍需 COUNT | 大部分查詢單頁 |
| 子查詢優化 | SELECT * FROM t WHERE id > (SELECT id FROM t ORDER BY id LIMIT 1000000,1) LIMIT 20 | 避免 OFFSET 掃描 | 需唯一索引、寫法複雜 | 深分頁必要時 |
| Keyset / Cursor Pagination | WHERE id > last_id ORDER BY id LIMIT 20 | 極快、無深分頁問題 | 無法跳頁、需唯一排序鍵 | 無限滾動、API 分頁 |
| 估算總數 | EXPLAIN rows / information_schema | 極快 | 不精確 | 顯示「約 N 筆」 |
<?php
function fetchPosts(PDO $pdo, ?int $cursor = null, int $limit = 20): array {
$sql = 'SELECT id, title, created_at FROM posts';
$params = [];
if ($cursor !== null) {
$sql .= ' WHERE id < ?';
$params[] = $cursor;
}
$sql .= ' ORDER BY id DESC LIMIT ?';
$params[] = $limit + 1; // 多取 1 筆判斷是否有下一頁
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
$hasMore = count($rows) > $limit;
if ($hasMore) array_pop($rows);
$nextCursor = $hasMore ? end($rows)['id'] : null;
return [
'data' => $rows,
'next_cursor' => $nextCursor,
'has_more' => $hasMore,
];
}
// 前端使用:傳入 next_cursor 獲取下一頁
<?php
function getTotalPosts(PDO $pdo): int {
$key = 'posts:total_count';
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
if ($redis->exists($key)) {
return (int)$redis->get($key);
}
$count = $pdo->query('SELECT COUNT(*) FROM posts')->fetchColumn();
$redis->setex($key, 300, $count); // 快取 5 分鐘
return $count;
}
// 寫入時 invalidates
$redis->del('posts:total_count');
// 傳統頁碼
?page=3&per_page=20&total=126
// Keyset(無限滾動)
?cursor=1000000&limit=20
// 混合:首頁用總數顯示頁碼,深頁自動切換 Keyset
<?php
// 原文邏輯:首頁查列表,若滿 20 筆再查 COUNT
// 改良:加入快取、Prepared Statement、錯誤處理
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;
$count = $_GET['count'] ?? null;
if ($count === null && $page === 1) {
$count = getTotalPosts($pdo); // 含快取
// 列表查詢
$stmt = $pdo->prepare('SELECT * FROM posts ORDER BY id DESC LIMIT ?, ?');
$stmt->execute([$offset, $perPage]);
$list = $stmt->fetchAll();
if (count($list) < $perPage) {
$count = count($list); // 實際筆數即為總數
}
} elseif ($page > 1) {
$count = (int)$_GET['count'];
$stmt = $pdo->prepare('SELECT * FROM posts ORDER BY id DESC LIMIT ?, ?');
$stmt->execute([$offset, $perPage]);
$list = $stmt->fetchAll();
}
// 產生分頁連結...
?>
原始來源:www.111cn.net