mysql表分区

drop table if exists test;

按月分区,按日分区类似

CREATE TABLE `test`

(
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
    `create_time` datetime NOT NULL  ,  
  PRIMARY KEY (`id`,`create_time`),
  KEY `idx_create (`create_time`)
) PARTITION BY RANGE (TO_DAYS(create_time))
(
PARTITION p202307 VALUES LESS THAN (TO_DAYS('2023-07-01')),
PARTITION p202308 VALUES LESS THAN (TO_DAYS('2023-08-01')),
PARTITION p35 VALUES LESS THAN MAXVALUE
)

注意:分区字段需要是主键,可以放到原主键后面成为复合主键。

通过explain或者desc 查询语句来检查分区是否生效

try {
    Date endDate= DateUtils.convert("2027-01-01","yyyy-MM-dd");
    Date date=DateUtils.convert("2023-07-01","yyyy-MM-dd");
    String str="PARTITION p%s VALUES LESS THAN (TO_DAYS('%s')),\r\n";
    StringBuilder sb=new StringBuilder();
    while (date.before(endDate)){
        sb.append(String.format(str, DateUtil.format(date,"yyyyMM"),DateUtil.format(date,"yyyy-MM-dd")));

        date=DateUtil.offsetMonth(date,1);
    }
    System.out.println(sb.toString());

} catch (ParseException e) {
    e.printStackTrace();
}

你可能感兴趣的:(mysql,数据库)