一、创键表时直接设置分区
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)
);