.分区相关SQL
/*查看数据表分区信息*/
EXPLAIN PARTITIONS SELECT * FROM [tablename] i where i.timeBETWEEN '2015-06-01 00:00:00' and '2015-06-31 00:00:00';
/*查询指定表的分区信息*/
select partition_name part,partition_expressionexpr,partition_description descr,table_rows from information_schema.partitions where TABLE_SCHEMA =schema() and TABLE_NAME='[tablename]';
/*重建指定表的指定分区*/
ALTER TABLE [tablename] REBUILD PARTITION[partitionname1,partitionname2,……]
/*整理表空间碎片*/
OPTIMIZE TABLE tablename(必须是多表空间)
/*查看当前mysql版本,因为某些内容5.5版本以前不支持*/
select VERSION();
/*查看当前MySQL的插件信息,查看当前mysql 分区是否可用*/
SELECT PLUGIN_NAME as Name,PLUGIN_VERSION as Version,PLUGIN_STATUS asStatus
FROMINFORMATION_SCHEMA.PLUGINS
WHERE PLUGIN_TYPE='STORAGEENGINE';
1. 创建表
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( ` id`int(10) unsigned NOT NULL AUTO_INCREMENT, ` time`datetime NOT NULL COMMENT '业务时间', PRIMARY KEY (`id`,` time`) ) ENGINE=InnoDB AUTO_INCREMENT=12001DEFAULT CHARSET=utf8 PARTITION BY RANGE (TO_DAYS(time)) (PARTITION part_201501 VALUES LESS THAN (TO_DAYS(‘2015-02-01’))ENGINE = InnoDB, PARTITION part_201502 VALUES LESS THAN (TO_DAYS(‘2015-03-01’))ENGINE = InnoDB, PARTITION part_201503 VALUES LESS THAN (TO_DAYS(‘2015-04-01’))ENGINE = InnoDB, PARTITION part_201504 VALUES LESS THAN (TO_DAYS(‘2015-05-01’))ENGINE = InnoDB, PARTITION part_201505 VALUES LESS THAN (TO_DAYS(‘2015-06-01’))ENGINE = InnoDB, PARTITION part_201506 VALUES LESS THAN (TO_DAYS(‘2015-07-01’))ENGINE = InnoDB) ;
【注】:其中使用两个字段作主键是因为MySQL要求有主键的必须对主键进行分区,或者表中没有主键,但是为了便于hibernate懒加载操作,我们需要这个id
2. 测试数据插入,可以通过JAVA写代码生成插入数据的sql语句,使用存储过程插入数据速度非常慢
3. 查看数据所在分区
EXPLAINPARTITIONS SELECT * FROM test t where t.time BETWEEN '2015-06-01 00:00:00' and'2015-06-31 00:00:00';(范围查询会查询第一个区块)
EXPLAIN PARTITIONS SELECT * FROM test t where t.time = '2015-06-0100:00:00';
4. 查看数据表分区数据分布信息
selectpartition_name part,partition_expression expr,partition_descriptiondescr,table_rows from information_schema.partitions where TABLE_SCHEMA =schema() and TABLE_NAME='test';
5. 使用navicat快速创建分区
设计表->选项->分割区
附1: 使用范围查询时,第一个分区必然会被扫描到,所以这就是为什么我们范围explain的时候都会看到都有第一分区
附2: Ctrl shift R 可以在navicat中快捷执行选中SQL语句
附3: 分区过程可能会很卡,想实时看到变化过程可以查看数据存储目录下的数据文件大小变化,另外删除表后进行的表空间碎片整理过程也可以在这里看到变化,具体可参考资料MySQL的表空间碎片整理