MySQL是一個(gè)開源的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),常用于Web應(yīng)用程序的數(shù)據(jù)存儲(chǔ)和管理。為了提高M(jìn)ySQL的查詢效率,經(jīng)常需要對(duì)數(shù)據(jù)進(jìn)行分表。下面介紹三種常見的MySQL分表方案:
方案一:按時(shí)間或編號(hào)分表
CREATE TABLE mytable_202101 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_202102 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_202103 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
方案二:按數(shù)據(jù)量分表
CREATE TABLE mytable_01 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_02 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_03 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE mytable_02 ENGINE=InnoDB; ALTER TABLE mytable_03 ENGINE=InnoDB; INSERT INTO mytable_02 SELECT * FROM mytable WHERE id >100000 AND id< 200000; INSERT INTO mytable_03 SELECT * FROM mytable WHERE id >= 200000;
方案三:按Hash值分表
CREATE TABLE mytable_0 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_1 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_2 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE mytable_3 ( id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, name VARCHAR(50) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO mytable_0 SELECT * FROM mytable WHERE MOD(ABS(MD5(id)), 4) = 0; INSERT INTO mytable_1 SELECT * FROM mytable WHERE MOD(ABS(MD5(id)), 4) = 1; INSERT INTO mytable_2 SELECT * FROM mytable WHERE MOD(ABS(MD5(id)), 4) = 2; INSERT INTO mytable_3 SELECT * FROM mytable WHERE MOD(ABS(MD5(id)), 4) = 3;
三種方案各有優(yōu)缺點(diǎn),需要根據(jù)業(yè)務(wù)需求進(jìn)行選擇。同時(shí),分表也會(huì)增加系統(tǒng)的復(fù)雜性,需要在設(shè)計(jì)時(shí)仔細(xì)考慮。
上一篇css 定位頭部