mysql的分区表

embedded/2025/3/1 3:52:17/

1.SQL表创建

下面以时间范围进行创建(每月一个分区,表中创建了四个月的分区)

创建:CREATE TABLE test_table (  id INT NOT NULL AUTO_INCREMENT,  content VARCHAR(255),  create_time DATETIME NOT NULL,PRIMARY KEY (id, create_time) 
) PARTITION BY RANGE (TO_DAYS(create_time)) (  PARTITION p20240601 VALUES LESS THAN (TO_DAYS('2024-06-01')),  PARTITION p20240701 VALUES LESS THAN (TO_DAYS('2024-07-01')),  PARTITION p20241801 VALUES LESS THAN (TO_DAYS('2024-08-01')),  PARTITION p20240901 VALUES LESS THAN (TO_DAYS('2024-09-01'))
);  查询分区详情:
SELECT *
FROM INFORMATION_SCHEMA.PARTITIONS 
WHERE TABLE_NAME = 'test_table';

2、mapper文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="*.infrastructure.mapper.TestTableMapper"><resultMap id="TestTable" type="*.domain.entity.TestTable"><id column="id" property="id" typeHandler="org.apache.ibatis.type.LongTypeHandler"/><result property="content" column="content" jdbcType="VARCHAR"/><result property="createTime" column="create_time" jdbcType="TIMESTAMP"typeHandler="org.apache.ibatis.type.LocalDateTimeTypeHandler"/></resultMap><!-- 创建新分区 --><update id="createNewPartition">ALTER TABLE TEST_TABLEADD PARTITION (  PARTITION ${partitionName} VALUES LESS THAN (TO_DAYS(#{lessThanValue})))</update><!-- 删除旧分区 --><update id="dropPartition">ALTER TABLE TEST_TABLEDROPPARTITION${partitionName}</update><!--查询是否存在分区--><select id="exitsPartition" resultType="boolean">SELECT COUNT(1) > 0FROM INFORMATION_SCHEMA.PARTITIONSWHERE TABLE_NAME = 'TEST_TABLE'AND PARTITION_NAME = #{partitionName}</select></mapper>

3、service

package *.domain.service;import *.domain.entity.TestTable;
import *.infrastructure.repo.TestTableRepository;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Random;@Service
public class TestTableService {@AutowiredTestTableRepository repository;// 插入数据,如果分区不存在,就创建分区,重新插入public void insert() {TestTable testTable = new TestTable();testTable.setContent("test");Random random = new Random();int i = Math.abs(random.nextInt()) % 365;LocalDateTime dateTime = LocalDateTime.now().minusDays(i);testTable.setCreateTime(dateTime);try {repository.getBaseMapper().insert(testTable);} catch (DataAccessException e) {LocalDate nextMonthFirstDay = YearMonth.from(dateTime).plusMonths(1).atDay(1);String lessThanValue = nextMonthFirstDay.format(DateTimeFormatter.ISO_DATE);String partitionName = "p" + lessThanValue.replaceAll("-", "");// 创建分区时加锁,如果是多节点,需要分布式锁synchronized (this) {if (!repository.getBaseMapper().exitsPartition(partitionName)) {repository.getBaseMapper().createNewPartition(partitionName, lessThanValue);}}repository.getBaseMapper().insert(testTable);}}// 创建分区public void createNewPartition(String partitionName, String lessThanValue) {repository.getBaseMapper().createNewPartition(partitionName, lessThanValue);}// 删除分区public void dropPartition(String partitionName) {repository.getBaseMapper().dropPartition(partitionName);}
}

----------------分割线-------------------------------

上述方法用代码来判断分区,新增分区,可能会引入一些奇奇怪怪的问题,因此,优化如下:

【针对mysql,使用mysql的定时事件】

1、首先确认mysql的时间调度器是否已经开启:

-- 查询事件调度器是否开启
SHOW VARIABLES LIKE 'event_scheduler'; -- 确保事件调度器已经开启  
SET GLOBAL event_scheduler = ON;  

2、写存储过程,用于创建新的分区, 这里是按天创建新的分区

DELIMITER //  CREATE PROCEDURE `AddDailyPartition`()  
BEGIN  DECLARE tomorrow DATE;  DECLARE partition_name VARCHAR(20);  -- 计算明天的日期  SET tomorrow = DATE_FORMAT(CURDATE() + INTERVAL 1 DAY, '%Y-%m-%d');  SET partition_name = CONCAT('p', DATE_FORMAT(tomorrow, '%Y%m%d'));  -- 构建ALTER TABLE语句来添加分区  SET @sql = CONCAT('ALTER TABLE TEST_TABLE ',  'ADD PARTITION (PARTITION ', partition_name,   ' VALUES LESS THAN (TO_DAYS('', tomorrow, '')))');  -- 执行ALTER TABLE语句  PREPARE stmt FROM @sql;  EXECUTE stmt;  DEALLOCATE PREPARE stmt;  
END //  DELIMITER ;  

3、创建定时事件,调用存储过程

-- 创建定时事件  
CREATE EVENT `CreateDailyPartition`  ON SCHEDULE EVERY 1 DAY STARTS TIMESTAMP(CURDATE())  DO CALL AddDailyPartition();  

4、查看已经创建的定时事件

SELECT * FROM information_schema.EVENTS; 在查看事件时,重要的列包括:
EVENT_NAME: 事件的名称。
EVENT_SCHEMA: 事件所属的数据库。
STATUS: 事件的状态,比如是否为ENABLED或DISABLED。
STARTS: 事件开始的时间。
ENDS: 事件结束的时间(如果有设置的话)。
LAST_EXECUTED: 事件上一次执行的时间。
EVENT_DEFINITION: 事件定义,即事件中要执行的SQL语句。

http://www.ppmy.cn/embedded/168957.html

相关文章

【网络编程】几个常用命令:ping / netstat / xargs / pidof / watch

ping&#xff1a;检测网络联通 1. ping 的基本功能2. ping 的工作原理3. ping 的常见用法4. ping 的输出解释5. ping 的应用场景6. 注意事项 netstat&#xff1a;查看网络状态 1. netstat 的基本功能2. 常见用法3. 示例4. 输出字段解释5. netstat 的替代工具6. 注意事项 xargs&…

【华为OD机考】华为OD笔试真题解析(15)--异常的打卡记录

题目描述 考勤记录是分析和考核职工工作时间利用情况的原始依据&#xff0c;也是计算职工工资的原始依据&#xff0c;为了正确地计算职工工资和监督工资基金使用情况&#xff0c;公司决定对员工的手机打卡记录进行异常排查。 如果出现以下两种情况&#xff0c;则认为打卡异常…

Nginx 报错:413 Request Entity Too Large

做web开发时&#xff0c;对于上传附件的功能&#xff0c;如果nginx没有调整配置&#xff0c;上传大一点的文件就会发生下面这种错误&#xff1a; 要解决上面的问题&#xff0c;只需要调整Nginx配置文件中的 client_max_body_size 参数即可&#xff0c;这个配置参数一般在http配…

行为型模式 - 职责链模式 (Chain of Responsibility Pattern)

行为型模式 - 职责链模式 (Chain of Responsibility Pattern) 职责链模式是一种行为设计模式&#xff0c;它允许你将请求沿着处理者链进行传递&#xff0c;直到有一个处理者能够处理该请求为止。以下是几个职责链模式的经典案例。 在企业中&#xff0c;员工请假需要不同级别的…

学习路程八 langchin核心组件 Models补充 I/O和 Redis Cache

前序 之前了解了Models&#xff0c;Prompt&#xff0c;但有些资料又把这块与输出合称为模型输入输出&#xff08;Model I/O&#xff09;‌&#xff1a;这是与各种大语言模型进行交互的基本组件。它允许开发者管理提示&#xff08;prompt&#xff09;&#xff0c;通过通用接口调…

WordPress网站502错误全面排查与解决指南

502 Bad Gateway错误是WordPress站长最常遇到的服务器问题之一,它意味着服务器作为网关或代理时,未能从上游服务器获取有效响应。针对WP可能出现的502问题,本文提供一些基础到进阶的解决方案供大家参考:) 一、502错误的本质和核心诱因 502错误属于HTTP状态码中的5xx系列,…

执行git操作时报错:`remote: [session-b8xxxda3] Access denied ...`解决方案

问题描述&#xff1a; 执行git push -u origin "master"时报错&#xff1a; > remote: [session-b849cda3] Access denied > fatal: unable to access https://gitee.com/jyunee/maibobo.git/: The requested URL returned error: 403表示没有权限访问远程仓库…

学习路程七 langchain核心组件 Prompt

前序 之前的ollama下载好了deepsseek-r1的镜像&#xff0c;运行了。我这电脑真慢的要死。之后要用这玩意儿还是回家用家里那个好点的电脑。 大致运行效果如下&#xff1a; 太吃配置了&#xff0c;建议有免费的还是用在线的吧。即使没有免费了充一点点&#x1f90f;&#x1f3…