1. 程式人生 > >mysql8.0 定時創建分區表記錄 每天定時創建下一天的分區表

mysql8.0 定時創建分區表記錄 每天定時創建下一天的分區表

數據 字段 decimal 包括 enc sts art locate incr

因單表數據太大, 需要表按時間分區 分區字段 pay_out_date 按天分 要求自動創建

1. 創建分區表

MYSQL的分區字段,必須包含在主鍵字段內

常見錯誤提示

錯誤提示:#1503
A PRIMARY KEY MUST INCLUDE ALL COLUMNS IN THE TABLE‘S PARTITIONING FUNCTION
MySQL主鍵的限制,每一個分區表中的公式中的列,必須在主鍵/unique key 中包括

CREATE TABLE `game_bet` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`create_date` DATETIME(6) DEFAULT NULL,

`create_person` VARCHAR(50) DEFAULT NULL,
`update_date` DATETIME(6) DEFAULT NULL,
`update_person` VARCHAR(50) DEFAULT NULL,
`bet_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`agent_code` VARCHAR(50) NOT NULL,
`game_id` INT(11) NOT NULL,
`game_name` VARCHAR(50) DEFAULT NULL,
`room_code` VARCHAR(11) NOT NULL,
`desk_code` VARCHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`user_id` BIGINT(20) NOT NULL,
`user_name` VARCHAR(50) NOT NULL,
`round_code` VARCHAR(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`commission` DECIMAL(18,3) NOT NULL,
`bet_amount` DECIMAL(18,3) NOT NULL,
`valid_bet_amount` DECIMAL(18,3) NOT NULL,
`pay_out` DECIMAL(18,3) NOT NULL,
`win_amount` DECIMAL(18,3) NOT NULL,
`settle_flag` INT(11) NOT NULL,
`device` INT(11) NOT NULL,
`login_ip` VARCHAR(50) NOT NULL,
`currency` VARCHAR(50) NOT NULL,
`bet_date` DATETIME(6) DEFAULT NULL,
`pay_out_date` DATETIME(6) NOT NULL DEFAULT ‘1970-01-01 00:00:00.000000‘,
`result` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`,`pay_out_date`),
KEY `IX_game_bet_agent_code` (`agent_code`),
KEY `IX_game_bet_create_date` (`create_date`),
KEY `IX_game_bet_device` (`device`),
KEY `IX_game_bet_game_id` (`game_id`),
KEY `IX_game_bet_pay_out_date` (`pay_out_date`),
KEY `IX_game_bet_round` (`round_code`)
) ENGINE=INNODB DEFAULT CHARSET=utf8
/*!50100 PARTITION BY RANGE (to_days(`pay_out_date`))
(PARTITION p20190421 VALUES LESS THAN (737535) ENGINE = InnoDB) */

2. 創建每日新增表分區的存儲過程

DELIMITER $$

USE `poker_games`$$

DROP PROCEDURE IF EXISTS `time_partition_procedure`$$

CREATE DEFINER=`root`@`%` PROCEDURE `time_partition_procedure`()
BEGIN

SELECT REPLACE(b.partition_name,‘p‘,‘‘) INTO @in_date FROM information_schema.PARTITIONS b WHERE b.table_name =‘game_bet‘ ORDER BY b.partition_ordinal_position DESC LIMIT 1;

SET @max_date= DATE_ADD(@in_date,INTERVAL 1 DAY)+0 ;

SET @date= DATE_ADD(@in_date,INTERVAL 1 DAY)+0 ;

SET @sql=CONCAT(‘ALTER TABLE game_bet add PARTITION (PARTITION p‘,@date,‘ VALUES LESS THAN (TO_DAYS(‘‘‘,@max_date,‘‘‘)));‘);

SELECT @sql;
SELECT @max_date;

PREPARE strsql FROM @sql; #預執行sql

EXECUTE strsql; #執行sql

DEALLOCATE PREPARE strsql; #釋放sql

COMMIT;

END$$

DELIMITER ;

3. 創建每天執行存儲的事件 明天淩晨3點執行

DELIMITER $$

CREATE EVENT `poker_games`.`time_partition_event`
ON SCHEDULE EVERY 1 DAY STARTS DATE_ADD(CURRENT_DATE+1,INTERVAL 3 HOUR)
ON COMPLETION PRESERVE
ENABLE DO
BEGIN
CALL time_partition_procedure();
END;

mysql8.0 定時創建分區表記錄 每天定時創建下一天的分區表