一、创键表时直接设置分区
create table your_table_name ( id int not null auto_increment, sale_date date not null, amount decimal(10, 2) not null, primary key (id, sale_date) ) partition by range columns(sale_date) ( partition p2020_01 values less than ('2020-02-01'), partition p2020_02 values less than ('2020-03-01'), partition p2020_03 values less than ('2020-04-01'), partition p2021_01 values less than ('2021-02-01'), partition p_max values less than (maxvalue) );
二、已有表分区
1、分区的前置条件
确保主键或唯一键包含分区键,若已经创建表可以修改
alter table your_table_name drop primary key; alter table your_table_name add primary key (id, xxdate);
2、分区操作
查询需要分区的日期字段所含有的年月
select distinct date_format(xxdate, '%y-%m') as ym from your_table_name order by ym;
根据上面sql语句查询的年月数据创建分区
# 我这只有202307、202308两个月数据 alter table your_table_name partition by range columns(xxdate) ( partition p2023_07 values less than ('2023-08-01'), partition p2023_08 values less than ('2023-09-01'), partition p_max values less than (maxvalue) );
三、验证
explain select * from your_table_name where xxdate between '2023-07-01' and '2023-07-31';
partitions 命中一个目标分区则分区成功,如:partitions列的值为 p2023_07
四、注意
如果有新的月份分区需要增加,则需要手动去修改,否则归为p_max分区影响查询效率
alter table your_table_name partition by range columns(xxdate) ( partition p2023_07 values less than ('2023-08-01'), partition p2023_08 values less than ('2023-09-01'), # 在这里添加 partition p_max values less than (maxvalue) );
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论