range分区列必须包含在主键中,而且列的每个分区都是一个值区间,每个值区间不能有交集,否则数据插入时,数据库无法确定应该插入到哪个表分区中。
1、已经创建的表添加range分区
分为4个区:p0、p1、p2、p3
p0:ext_int<100;
p1:100<=ext_int<200;
p2:200<=ext_int<300;
p3:ext_int>=300;
CREATE TABLE `test_user_range` (
`user_id` bigint(19) NOT NULL,
`user_name` varchar(50) NOT NULL,
`ext_int` int(2) NOT NULL,
`ext_str` int(2) NOT NULL,
`ts` bigint(19) NOT NULL,
PRIMARY KEY (`user_id`,`ext_int`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ;
ALTER TABLE test_user_range PARTITION BY RANGE(ext_int)(
PARTITION p0 VALUES less than (100),
PARTITION p1 VALUES less than (200),
PARTITION p2 VALUES less than (300),
PARTITION p3 VALUES less than MAXVALUE
);
执行结果:
2、直接创建分区表
CREATE TABLE `test_user_range` (
`user_id` bigint(19) NOT NULL,
`user_name` varchar(50) NOT NULL,
`ext_int` int(2) NOT NULL,
`ext_str` int(2) NOT NULL,
`ts` bigint(19) NOT NULL,
PRIMARY KEY (`user_id`,`ext_int`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
PARTITION BY RANGE(ext_int)(
PARTITION p0 VALUES less than (100),
PARTITION p1 VALUES less than (200),
PARTITION p2 VALUES less than (300),
PARTITION p3 VALUES less than MAXVALUE
);
结果如下:
3、插入测试数据
INSERT INTO test_user_range(user_id,user_name,ext_int,ext_str,ts)VALUES
(1,'user_name1',50,'50',UNIX_TIMESTAMP()),
(2,'user_name2',99,'99',UNIX_TIMESTAMP()),
(3,'user_name3',100,'100',UNIX_TIMESTAMP()),
(4,'user_name4',500,'500',UNIX_TIMESTAMP());
预期:p0有2条记录,p1有1条记录,p2没有记录,p3有1条记录
查询sql:
SELECT
PARTITION_NAME,
PARTITION_DESCRIPTION,
TABLE_ROWS
FROM
information_schema.`PARTITIONS`
WHERE
table_name = 'test_user_range';
结果如下:
和预期相符。