MySQL 僅支援 Nested Loop Join(嵌套循環連接),理解其「外層驅動表 → 內層被驅動表」的執行模型,是 JOIN 優化的核心鑰匙。本文從原理、EXPLAIN 解讀、索引策略、Buffer 調優、SQL 改寫五個維度系統闡述。
三表 JOIN 示例:
SELECT m.subject, c.content
FROM user_group g
JOIN group_message m ON m.group_id = g.group_id
JOIN group_message_content c ON c.group_msg_id = m.id
WHERE g.user_id = 1;
執行偽代碼:
for g_rec in (SELECT * FROM user_group WHERE user_id = 1): -- 驅動表
for m_rec in (SELECT * FROM group_message WHERE group_id = g_rec.group_id): -- 被驅動表1
for c_rec in (SELECT * FROM group_message_content WHERE group_msg_id = m_rec.id): -- 被驅動表2
output(g_rec.user_id, m_rec.subject, c_rec.content)
EXPLAIN SELECT ...\G
*************************** 1. row *************************** -- 驅動表
table: g
type: ref
key: user_group_uid_ind
rows: 2
Extra:
*************************** 2. row *************************** -- 被驅動表1
table: m
type: ref
key: idx_group_message_gid_uid
rows: 3
Extra:
*************************** 3. row *************************** -- 被驅動表2
table: c
type: ref
key: idx_group_message_content_msg_id
rows: 2
Extra:
刪除 group_message_content.group_msg_id 索引後:
table: c
type: ALL -- 全表掃描!
key: NULL
rows: 96
Extra: Using where; Using join buffer
Join Buffer 機制:
for g_rec in user_group:
for m_rec in group_message:
put (g_rec, m_rec) into join_buffer
if buffer_full: flush_buffer()
flush_buffer():
for c_rec in group_message_content: -- 全表掃描
for buffered in join_buffer:
if c_rec.group_msg_id == buffered.m_rec.id:
output(...)
type=ALL/index/range/index_mergejoin_buffer_size 控制(預設 256KB,會話級)
-- 子查詢:建立臨時表,性能差
SELECT * FROM customerinfo
WHERE CustomerID NOT IN (SELECT CustomerID FROM salesinfo);
-- LEFT JOIN + IS NULL:無臨時表,利用索引
SELECT * FROM customerinfo
LEFT JOIN salesinfo ON customerinfo.CustomerID = salesinfo.CustomerID
WHERE salesinfo.CustomerID IS NULL;
錯誤:The SELECT would examine more than MAX_JOIN_SIZE rows
SET SQL_BIG_SELECTS=1 或 SET SQL_MAX_JOIN_SIZE=#type=ALL 變為 ref,根治
-- 原始:大表 JOIN 後再過濾
SELECT w.*, r.sound_url
FROM sti_words w
LEFT JOIN sti_word_list_ja r ON w.word = r.word
WHERE w.insert_date = '2010-11-16' AND w.user_id = 54
GROUP BY w.word ORDER BY w.id LIMIT 30;
-- 優化:子查詢先過濾主表,再 JOIN 小結果集
SELECT ww.*, r.sound_url
FROM (
SELECT * FROM sti_words
WHERE insert_date = '2010-11-16' AND user_id = 54
) ww
LEFT JOIN sti_word_list_ja r ON ww.word = r.word
GROUP BY ww.word ORDER BY ww.id LIMIT 30;
STRAIGHT_JOIN 強制指定順序type=ref 是標配,ALL 觸發 Join Buffer 災難SET SESSION join_buffer_size = 8M,減少 flush 次數,治標不治本user_group(user_id))group_message(group_id)、group_message_content(group_msg_id))(WHERE條件列, 關聯列) 或 (關聯列, WHERE條件列) 視選擇率而定SELECT 列全部在索引中,避免回表MySQL 8.0.18+ 引入 Hash Join(無索引時自動啟用),大表關聯無需 Join Buffer 即可高效執行。但索引驅動的 Nested Loop 仍是首選,Hash Join 為無索引場景托底。
JOIN 優化的本質:用索引將 O(M×N) 的嵌套循環降為 O(M + N) 的索引查找。讀懂 EXPLAIN 的 type/rows/Extra,佈局正確索引,控制驅動順序,是寫出高性能 JOIN 的唯一正道。