給定當前文章 ID $article_id 與分類 ID $cat_id,查詢同分類下 ID 最近的上一篇(最大 ID < 當前)與下一篇(最小 ID > 當前)。
SELECT article_id, title
FROM article
WHERE article_id = (
SELECT MAX(article_id)
FROM article
WHERE article_id < $article_id AND cat_id = $cat_id
);
SELECT article_id, title
FROM article
WHERE article_id = (
SELECT MIN(article_id)
FROM article
WHERE article_id > $article_id AND cat_id = $cat_id
);
優點: 語義清晰,利用索引 (cat_id, article_id) 可極快定位。
缺點: 需兩次往返數據庫(或應用層拼接兩條 SQL)。
-- 上一篇
SELECT id FROM article WHERE id < 10 ORDER BY id DESC LIMIT 1;
-- 下一篇
SELECT id FROM article WHERE id > 10 LIMIT 1;
未帶分類過濾,且 ORDER BY ... LIMIT 1 在無索引或索引不匹配時會全表掃描排序,性能差。
前提:三個子查詢列結構完全一致。
(SELECT id, title FROM article WHERE id < 10 AND cat_id = 5 ORDER BY id DESC LIMIT 1)
UNION ALL
(SELECT id, title FROM article WHERE id = 10 AND cat_id = 5)
UNION ALL
(SELECT id, title FROM article WHERE id > 10 AND cat_id = 5 ORDER BY id ASC LIMIT 1);
結果順序: 第 1 行 = 上一篇,第 2 行 = 當前,第 3 行 = 下一篇。
優勢: 單次網絡往返,應用層一次獲取三條數據,減少延遲。
ALTER TABLE article ADD INDEX idx_cat_id_article_id (cat_id, article_id);
(cat_id, article_id) 同時支援:cat_id = ?article_id < ? / article_id > ?ORDER BY article_id DESC/ASC(無需 filesort)(cat_id, publish_time, article_id)。「上一篇/下一篇」核心是鄰近值查找。推薦使用複合索引 + 子查詢保證單查詢毫秒級響應;若需降低網絡延遲,採用 UNION ALL 合併三查詢。避免無索引的 ORDER BY ... LIMIT 全表掃描。