文章目录
- 一、根据时间创建分区
- 二、根据业务主键id创建分区
一、根据时间创建分区
创建时间分区表
CREATE TABLE `table_time`(`ID` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',`STA_ID` int(11) NULL DEFAULT NULL COMMENT '业务ID',`STA_NAME` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '业务名称',`MONITOR_TIME` datetime(0) NOT NULL COMMENT '监测时间',PRIMARY KEY (`ID`,`MONITOR_TIME`) USING BTREE) ENGINE = InnoDB AUTO_INCREMENT = 2111262 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '测试表' ROW_FORMAT = Dynamicpartition by range (to_days(MONITOR_TIME)) ( PARTITION p0 VALUES LESS THAN (TO_DAYS('2023-05-01')),PARTITION p1 VALUES LESS THAN (TO_DAYS('2023-06-01')) );
查看分区是否生效
select partition_name part, partition_expression expr, partition_description descr, table_rows fromINFORMATION_SCHEMA.partitionswhere TABLE_SCHEMA="库名" AND TABLE_NAME="表名";
时间格式化
ps:由于我们是以时间作为分区,时间会被转成特殊的数字,所以如果想要查看分区属于哪个时间,还需要格式化下时间数据才可以查看
SELECT DATE_SUB(DATE_ADD('0000-01-01', INTERVAL 740543 DAY), INTERVAL 1 DAY);
二、根据业务主键id创建分区
创建业务主键分区表
CREATE TABLE `table_id`(`id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键字符串',`car_id` int(11) NOT NULLCOMMENT '车辆ID',`car_no` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '车牌号') ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '车辆行驶轨迹' ROW_FORMAT = DynamicPARTITION BY LIST COLUMNS(car_id)(PARTITION p0 VALUES IN (0) ENGINE = InnoDB);
根据业务主键添加分区
ALTER TABLE table_id ADD PARTITION (PARTITION p_197401 VALUES IN (197401) ENGINE = InnoDB);
插入数据
ps:插入数据的时候,可以指定分区。如果不指定分区,也会自行根据分区入库。
insert into table_id partition(p_197401) (car_id,car_no)values XXXXX;