單表超過百萬行查詢效能急劇下降、鎖衝突頻發。水平分表將邏輯大表拆分為多個物理子表。本文系統梳理四大分表策略、適用場景、代碼實現與避坑指南。
-- 適用:日誌、流水、訊息、強時效性業務
-- 表名:logs_202401, logs_202402 ...
-- 查詢路由:WHERE create_time BETWEEN '2024-01-01' AND '2024-01-31' → logs_202401
優點:天然歸檔、冷熱分離、Drop 老分表極快;缺點:跨月查詢需 UNION、非時間維度查詢掃全部分表。
-- 適用:嚴格自增 ID、用戶表、訂單表
-- table_1: id 1~100W, table_2: 100W~200W ...
-- 路由:WHERE user_id BETWEEN 1000001 AND 2000000 → table_2
優點:範圍查詢高效、擴容只需加新表;缺點:熱點集中在最新分表、ID 耗盡需擴容。
// PHP 取模分表 (N 張表)
function hash_table($table, $user_id, $total) {
return $table . '_' . (($user_id % $total) + 1);
}
echo hash_table('article', 1234, 5); // article_5
// CRC32 版 (分布更均勻)
function get_hash_table($table, $userid) {
$str = crc32($userid);
$hash = ($str < 0) ? '0'.substr(abs($str),0,1) : substr($str,0,2);
return $table . '_' . $hash;
}
優點:資料均勻、無熱點、擴容需 Rehash (一致性 Hash 可緩解);缺點:範圍查詢需全分表掃描。
UNION=(t1,t2) INSERT_METHOD=LAST)pt-online-schema-change / gh-ost應用層手動路由維護成本高,建議引入 ShardingSphere / MyCat / Vitess / ProxySQL 做透明分片,專注業務開發。