查詢所需的所有欄位都包含在索引中,執行計畫 `Extra` 欄顯示 Using index,不需回表查詢資料行,大幅減少 I/O。
-- 原查詢
SELECT a FROM t WHERE b = 100;
-- 單獨在 b 建索引:索引定位 → 回表取 a → 兩次 I/O
-- 優化:建立複合索引 (b, a)
ALTER TABLE t ADD INDEX idx_b_a (b, a);
-- 執行計畫顯示 Using index,直接從索引葉節點取得 a,零回表
SELECT COUNT(*) FROM articles WHERE category_id = 5;
-- category_id 索引即為覆蓋索引(COUNT(*) 不需讀取行資料)
-- 原寫法:LIMIT 10000, 10 需掃描 10000 行
SELECT id, title, content FROM articles ORDER BY created DESC LIMIT 10000, 10;
-- 優化:子查詢只取 id(覆蓋索引 created, id),再 JOIN 回表取內容
SELECT a.id, a.title, a.content
FROM articles a
INNER JOIN (
SELECT id FROM articles ORDER BY created DESC LIMIT 10000, 10
) b USING (id)
ORDER BY a.created DESC;
-- 建立複合索引 (created, id) 使子查詢走覆蓋索引,極速定位 id
EXPLAIN SELECT ...;
-- 關鍵看 Extra 欄:Using index = 覆蓋索引生效