Mysql创建分区

MySQL创建分区总结:

我们项目中用的分区,大部分都是按时间字段去进行分区,如果是没有数据的表,我们可以重建了,而如果有数据的话只能建临时表,在临时表中建好分区,再用select into到临时表,或者先从原表导出数据重建表,等建好分区再导入也可以,下面是用临时表的方法:

-- 创建一张与cnzz_count样的临时表temp_cnzz_count,把要分区的字段也设置为主键
-- 并在临时表分区,执行下列语句时会把已建好的分区重建
alter table temp_cnzz_count partition by range(to_days(data_time))
(
partition p20150601 values less than (to_days('2015-06-01')),
partition p20150602 values less than (to_days('2015-06-02')),
partition p20150603 values less than (to_days('2015-06-03')),
partition p20150604 values less than (to_days('2015-06-04')),
partition p20150605 values less than (to_days('2015-06-05')),
partition p20150606 values less than (to_days('2015-06-06'))
);
select count(*) from cnzz_count
-- 查看分区
SELECT * FROM information_schema.PARTITIONS WHERE table_name='temp_cnzz_count';
-- 如果数据不大可以考虑用下面的语句把主表数据复制到临时表
Insert into temp_cnzz_count select * from cnzz_count;

select count(*) from temp_cnzz_count
-- 复制完数据后,把主表删除了,把临时表重命名为主表的名字就OK了temp_cnzz_count
-- 用下面的语句测试查询是否走分区,如果有,则分区成功
EXPLAIN partitions select * from temp_cnzz_count where data_time = '2015-05-20'

-- 查看表中的分区

SELECT * FROM information_schema.PARTITIONS WHERE table_name='cnzz_count';


当我们想给已经分区好的表中加入一个分区时,用下面语句

-- 新增分区(注意:不能在最新的分区前面加分区,只能加入到最新的后面)
ALTER TABLE cnzz_count ADD PARTITION (PARTITION p20150524 VALUES LESS THAN (to_days('2015-05-24')))


当然我们要用list创建分区可以如下写法:

alter table site_temp partition by list(first_trade_id)
(
partition s0 values in (-1),
partition s1 values in (1),
partition s2 values in (2),
partition s3 values in (3),
partition s4 values in (4),
partition s5 values in (5)

);


发布了44 篇原创文章 · 获赞 23 · 访问量 16万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章