CREATETABLE single_tbl( id int, name varchar(30), primarykey(id) ); show topology from single_tbl;
1 2 3 4 5
CREATETABLE normal_table( id int, name varchar(30), primarykey(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
分库不分表
假设已经建好的分库数为 8,建一张表,只分库不分表,分库方式为根据 id 列哈希。
1 2 3 4 5 6 7
CREATETABLE multi_db_single_tbl( id int, name varchar(30), primarykey(id) ) dbpartition by hash(id);
show topology from multi_db_single_tbl;
分库分表
使用哈希函数做拆分
1 2 3 4 5 6 7 8
CREATETABLE multi_db_multi_tbl( id int auto_increment, bid int, name varchar(30), primarykey(id) ) dbpartition by hash(id) tbpartition by hash(bid) tbpartitions 3;
show topology from multi_db_multi_tbl;
使用双字段哈希函数做拆分
1 2 3 4 5 6 7 8 9
createtable test_order_tb ( id int, seller_id varchar(30) DEFAULTNULL, buyer_id varchar(30) DEFAULTNULL, create_time datetime DEFAULTNULL, primarykey(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 dbpartition by RANGE_HASH(seller_id,buyer_id, 10) tbpartition by RANGE_HASH(seller_id,buyer_id, 10) tbpartitions 3;
show topology from multi_db_multi_tbl;
使用日期做拆分
可以使用日期函数 MM/DD/WEEK/MMDD 来作为分表的拆分算法
1 2 3 4 5 6 7 8
CREATETABLE user_log( userId int, name varchar(30), operation varchar(30), actionDate DATE ) dbpartition by hash(userId) tbpartition by WEEK(actionDate) tbpartitions 7;
show topology from user_log;
1 2 3 4 5 6 7 8 9
CREATETABLE user_log2( userId int, name varchar(30), operation varchar(30), actionDate DATE ) dbpartition by hash(userId) tbpartition by MM(actionDate) tbpartitions 12;
show topology from user_log2;
默认使用主键作为拆分字段
当拆分算法不指定任何拆分字段时,系统默认使用主键作为拆分字段。
1 2 3 4 5
CREATETABLE prmkey_tbl( id int, name varchar(30), primarykey(id) ) dbpartition by hash();
1 2 3 4 5
CREATETABLE prmkey_multi_tbl( id int, name varchar(30), primarykey(id) ) dbpartition by hash() tbpartition by hash() tbpartitions 3;