mysql(41) : 自动分区

创建分区

初始化分区(时间字段需要设置为主键)

alter table test1 partition by range (TO_DAYS(create_time))(
    partition p20210420 values less than(738265 ),
  	partition p20210421 values less than(738266 )
);

初始化今日分区

DELIMITER  //
drop procedure if exists append_partition_init;
CREATE PROCEDURE `append_partition_init`() 
     COMMENT '初始化分区' 
BEGIN
     SET @today_partition_name = (SELECT concat('p',DATE_FORMAT(now(),'%Y%m%d')));
     SET @today_no = (SELECT TO_DAYS(now() ));
     
     SET @test_init_partition_sql=CONCAT('ALTER TABLE test partition by range (TO_DAYS(create_time))( partition ',@today_partition_name,' values less than(',@today_no,' ));');
         PREPARE stmt FROM @test_init_partition_sql;
         EXECUTE stmt;
END 
//

自动创建明日分区

DELIMITER  //
drop procedure if exists append_partition;
CREATE PROCEDURE `append_partition`() 
	COMMENT '追加分区' 
BEGIN
	SET @tomorrow_partition_name = (SELECT concat('p',DATE_FORMAT(date_add(now(), interval 1 day),'%Y%m%d')));
	SET @tomorrow_no = (SELECT TO_DAYS(date_add(now(), interval 1 day) ));

	SET @test_append_partition_sql=CONCAT('ALTER TABLE device_status ADD PARTITION ( partition ',@tomorrow_partition_name,' values less than(',@tomorrow_no,' ))');
    PREPARE stmt FROM @test_append_partition_sql;
    EXECUTE stmt;
	
    DEALLOCATE PREPARE stmt;
END 
//

创建今日分区

DELIMITER  //
drop procedure if exists append_partition_init;
CREATE PROCEDURE `append_partition_init`() 
	COMMENT '追加分区' 
BEGIN
	SET @today_partition_name = (SELECT concat('p',DATE_FORMAT(now(),'%Y%m%d')));
	SET @today_no = (SELECT TO_DAYS(now() ));

	SET @test_append_partition_sql=CONCAT('ALTER TABLE device_status ADD PARTITION ( partition ',@today_partition_name,' values less than(',@today_no,' ))');
    PREPARE stmt FROM @test_append_partition_sql;
    EXECUTE stmt;
	
    DEALLOCATE PREPARE stmt;
END 
//

定时事件

DELIMITER  //
drop event  if EXISTS append_partition_task;
CREATE EVENT `append_partition_task` 
  ON SCHEDULE EVERY 1 DAY 
  STARTS  '2021-04-20 15:50:00'  ON COMPLETION NOT PRESERVE  
  ENABLE  
  COMMENT '每天创建明天分区'  
  DO begin
call append_partition();

end
//

删除分区

获取今天之前的分区号列表

select partition_name
  from information_schema.partitions
 where table_schema= schema()  and table_name= 'test'
   and partition_description < (to_days(now())-1);

拼接分区

String ps = String.join(",", list);

批量删除分区

ALTER TABLE ${table} DROP PARTITION p1,p2;

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