
使用分区的好处不用多说了,懂得都懂。
1)如果想在创建表的时候创建分区我们可以如下写法:
下面以时间日期分区
CREATE TABLE test_partition(
id int(11) not null ,
tran_date date not null ,
amt decimal(17,2) not null ,
primary key(id,tran_date) //注意,如果想根据某个列分区,必须将此列加入主键中
)
partition by range(to_days(tran_date))(
partition p_20210928 values less than (to_days('2021-09-29')),
partition p_20210929 values less than (to_days('2021-09-30')),
partition p_max values less than maxvalue
);
下面看下20210928的查询计划:
可以看到分区起到作用了。
2)如果表已经存在了,我们可以通过下面的语句给表新建分区:
ALTER TABLE test_partition PARTITION by range(to_days(tran_date))(
partition p_20210928 values less than (to_days('2021-09-29')),
partition p_20210929 values less than (to_days('2021-09-30')),
partition p_20210930 values less than (to_days('2021-10-01')),
partition p_max values less than maxvalue
);
查看对9月30号的查询计划,可以看到成功创建分区了
1)首先mysql不支持删除一个分区后重新创建该分区(除非该分区是最大分区)
以下面的表为例:
CREATE TABLE test_partition(
id int(11) not null ,
tran_date date not null ,
amt decimal(17,2) not null ,
primary key(id,tran_date) //注意,如果想根据某个列分区,必须将此列加入主键中
)
partition by range(to_days(tran_date))(
partition p_20210928 values less than (to_days('2021-09-29')),
partition p_20210929 values less than (to_days('2021-09-30')),
partition p_max values less than maxvalue
);
首先我们删除分区p_20210929 :
alter table test_partition drop partition p_20210929;
然后查看该表的分区:
可以看到分区p_20210929已经被删除了,下面我们向表中重新添加这个分区,看看可以不可以:
alter table test_partition add partition(
partition p_20210929 values less than (to_days('2021-09-30'))
)
答案是不可以的。
下面我们删除最大分区后添加看看可不可以:
alter table test_partition drop partition p_max;
删除成功!!
下面进行添加:
alter table test_partition add partition( partition p_max values less than maxvalue )
可以看到,添加成功!!