Mysql自動按月表分割槽
很久沒有碰DB了。最近需要做一個日誌表,因此重新拾了下。實現了下自動按月表分割槽
開發環境為Mysql 5.7.28
參考資料:
Mysql分割槽表及自動建立分割槽Partition(按日)
核心的兩個儲存過程:
auto_create_partition為建立表分割槽,呼叫後為該表建立到下月結束的表分割槽。
auto_del_partition為刪除表分割槽,方便歷史資料空間回收。
DELIMITER $$
DROP PROCEDURE IF EXISTS auto_create_partition$$
CREATE PROCEDURE `auto_create_partition`(IN `table_name` varchar(64))
BEGIN
SET @next_month:=CONCAT(date_format(date_add(now(),interval 2 month),'%Y%m'),'01');
SET @SQL = CONCAT( 'ALTER TABLE `', table_name, '`',
' ADD PARTITION (PARTITION p', @next_month, " VALUES LESS THAN (TO_DAYS(",
@next_month ,")) );" );
PREPARE STMT FROM @SQL;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END$$
DROP PROCEDURE IF EXISTS auto_del_partition$$
CREATE PROCEDURE `auto_del_partition`(IN `table_name` varchar(64),IN `reserved_month` int)
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_part_name varchar(100) DEFAULT "";
DECLARE part_cursor CURSOR FOR
select partition_name from information_schema.partitions where table_schema = schema()
and table_name=@table_name and partition_description < TO_DAYS(CONCAT(date_format(date_sub(now(),interval reserved_month month),'%Y%m'),'01'));
DECLARE continue handler FOR
NOT FOUND SET v_finished = TRUE;
OPEN part_cursor;
read_loop: LOOP
FETCH part_cursor INTO v_part_name;
if v_finished = 1 then
leave read_loop;
end if;
SET @SQL = CONCAT( 'ALTER TABLE `', table_name, '` DROP PARTITION ', v_part_name, ";" );
PREPARE STMT FROM @SQL;
EXECUTE STMT;
DEALLOCATE PREPARE STMT;
END LOOP;
CLOSE part_cursor;
END$$
DELIMITER ;
下面是示例
-- 假設有個表叫records,設定分割槽條件為按end_time按月分割槽
DROP TABLE IF EXISTS `records`;
CREATE TABLE `records` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`start_time` datetime NOT NULL,
`end_time` datetime NOT NULL,
`memo` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
PRIMARY KEY (`id`,`end_time`)
)
PARTITION BY RANGE (TO_DAYS(end_time))(
PARTITION p20200801 VALUES LESS THAN ( TO_DAYS('20200801'))
);
DROP EVENT IF EXISTS `records_auto_partition`;
-- 建立一個Event,每月執行一次,同時最多儲存6個月的資料
DELIMITER $$
CREATE EVENT `records_auto_partition`
ON SCHEDULE EVERY 1 MONTH ON COMPLETION PRESERVE
ENABLE
DO
BEGIN
call auto_create_partition('records');
call auto_del_partition('records',6);
END$$
DELIMITER ;
幾點注意事項:
對於Mysql 5.1以上版本來說,表分割槽的索引欄位必須是主鍵
儲存過程中,DECLARE 必須緊跟著BEGIN,否則會報看不懂的錯誤
遊標的DECLARE需要在定義宣告之後,否則會報錯
如果是自己安裝的Mysql,有可能Event功能是未開啟的,在建立Event時會提示錯誤;修改my.cnf,在 [mysqld] 下新增event_scheduler=1後重啟即可。
————————————————
版權宣告:本文為CSDN博主「無邊風月-風之羽翼」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/gogoytgo/article/details/108267105