首先说明一点:mysql的版本使用的是5.6,完整的sql操作表分区的语句如下:
-- 1.删除表
drop table t_test;
-- ===================================================================================
-- 2.创建一个表并对其分区,被创建分区的字段必须为主键,或者创建分区时表中没有主键
-- 2.1 方式一:表和分区一起创建
create table t_test (
id int,
dates timestamp
)partition by range (unix_timestamp(dates)) (
-- 小于2018-01-01的
partition p1 values less than (unix_timestamp('2018-01-01'))
,partition p2 values less than (unix_timestamp('2018-02-01'))
,partition p3 values less than (unix_timestamp('2018-03-01'))
,partition p4 values less than maxvalue
);
-- ===================================================================================
-- 2.2 方式二:表和分区分开创建
-- 2.2.1 建表
create table `t_test` (
`id` int(11) not null,
`dates` timestamp not null default '0000-00-00 00:00:00' on update current_timestamp,
primary key (`id`,`dates`)
);
-- 3. 修改分区信息
alter table t_test partition by range (unix_timestamp(dates)) (
-- 第一组小于2018-01-01的
partition p1 values less than (unix_timestamp('2018-01-01')),
partition p2 values less than (unix_timestamp('2018-02-01')),
partition p3 values less than (unix_timestamp('2018-03-01')),
partition p4 values less than (unix_timestamp('2018-04-01')),
partition p5 values less than maxvalue
);
-- ===================================================================================
-- 4. 删除并添加新的分区(注意:如果原先最后一个分区是partition pnow values less than maxvalue; 那么应该先删除该分区,然后在执行新增分区语句,然后再新增回该分区)
-- 4.1 删除一个分区(注意:删除一个分区时,该分区内的所有数据也都会被删除;)
alter table t_test drop partition p5;
-- 4.2 新增一个分区
alter table t_test add partition (partition p6 values less than (unix_timestamp('2018-05-01')));
-- 4.3 新增一个分区(不满足其余分区条件的都存放在这个分区)
alter table t_test add partition (partition p7 values less than maxvalue);
-- ===================================================================================
-- 5.查询这个表有多少分区
-- 5.1查询每一个分区对应的数量
select
partition_name,partition_description,
from_unixtime(partition_description,'%Y-%m-%d') expirydate,table_rows
from
information_schema.`partitions` where table_name = 't_test';
-- 6.创建测试数据
insert into `t_test` values ('4', '2016-01-02 15:00:00');
insert into `t_test` values ('1', '2018-01-02 15:00:00');
insert into `t_test` values ('5', '2018-01-02 16:00:00');
insert into `t_test` values ('2', '2018-02-03 15:00:00');
insert into `t_test` values ('3', '2018-04-03 15:00:00');
-- 6.查询数据
select * from t_test;
我们使用第5步的sql可以查看分区信息
参考:https://blog.csdn.net/liguoqingxjxcc/article/details/82978279