MySQL使用分区表的好处:
1 mysql> CREATE TABLE sale_data ( 2 -> sale_date DATETIME NOT NULL, 3 4 -> sale_item VARCHAR(2) NOT NULL , 5 6 -> sale_money DECIMAL(10,2) NOT NULL 7 8 -> ) www.2cto.com 9 10 -> PARTITION BY RANGE (YEAR(sale_date)*100+MONTH(sale_date)) (11 12 -> PARTITION p201001 VALUES LESS THAN (201002),13 14 -> PARTITION p201002 VALUES LESS THAN (201003),15 16 -> PARTITION p201003 VALUES LESS THAN (201004),17 18 -> PARTITION p201004 VALUES LESS THAN (201005),19 20 -> PARTITION p201005 VALUES LESS THAN (201006),21 22 -> PARTITION p201006 VALUES LESS THAN (201007),23 24 -> PARTITION p201007 VALUES LESS THAN (201008),25 26 -> PARTITION p201008 VALUES LESS THAN (201009),27 28 -> PARTITION p201009 VALUES LESS THAN (201010),29 30 -> PARTITION pcatchall VLAUES LESS THAN MAXVALUE31 -> );32 33 Query OK, 0 rows affected (0.20 sec)
新增分区
mysql> ALTER TABLE sale_data -> ADD PARTITION (PARTITION p201010 VALUES LESS THAN (201011)); Query OK, 0 rows affected (0.36 sec)Records: 0 Duplicates: 0 Warnings: 0
删除分区
--当删除了一个分区,也同时删除了该分区中所有的数据。mysql> ALTER TABLE sale_data DROP PARTITION p201010;Query OK, 0 rows affected (0.22 sec) www.2cto.com Records: 0 Duplicates: 0 Warnings: 0
分区的合并
下面的SQL,将p201001 - p201009 合并为3个分区p2010Q1 - p2010Q3
mysql> ALTER TABLE sale_data -> REORGANIZE PARTITION p201001,p201002,p201003, -> p201004,p201005,p201006, -> p201007,p201008,p201009 INTO -> ( -> PARTITION p2010Q1 VALUES LESS THAN (201004), -> PARTITION p2010Q2 VALUES LESS THAN (201007), -> PARTITION p2010Q3 VALUES LESS THAN (201010) -> ); Query OK, 0 rows affected (1.14 sec)Records: 0 Duplicates: 0 Warnings: 0
分区的拆分
下面的SQL,将p2010Q1 分区,拆分为s2009 与s2010 两个分区
mysql> ALTER TABLE sale_data REORGANIZE PARTITION p2010Q1 INTO ( -> PARTITION s2009 VALUES LESS THAN (201001), www.2cto.com -> PARTITION s2010 VALUES LESS THAN (201004) -> ); Query OK, 0 rows affected (0.36 sec)Records: 0 Duplicates: 0 Warnings: 0
一个利用不同物理位置数据源做分区的例子:
CREATE TABLE ts (id INT, purchased DATE) ENGINE=innodb PARTITION BY RANGE(YEAR(purchased)) SUBPARTITION BY HASH(id) ( PARTITION p0 VALUES LESS THAN (1990) ( SUBPARTITION s0 //在大的分区下又有小的分区 DATA DIRECTORY='/usr/local/mysql/data0' //数据源 INDEX DIRECTORY='/usr/local/mysql/index0', //索引数据源 SUBPARTITION s1 DATA DIRECTORY='/usr/local/mysql/data1' INDEX DIRECTORY='/usr/local/mysql/index1' ), PARTITION p1 VALUES LESS THAN (MAXVALUE) ( SUBPARTITION s2 DATA DIRECTORY='/usr/local/mysql/data1' INDEX DIRECTORY='/usr/local/mysql/index1', SUBPARTITION s3 DATA DIRECTORY='/usr/local/mysql/data2' INDEX DIRECTORY='/usr/local/mysql/index2' ) );