MySQL创建分区表相关


背景:一个记录表,类似日志的信息,查询大量集中在某个用户个人的数据,分区需要尽量保证一个人的数据在一个分区里。因此采用通过user_id进行hash分区的方式。

-- 将分区字段添加为主键
alter table logs modify column id int not null;
alter table logs drop primary key;
alter table logs add primary key(id, user_id);
alter table logs modify column id int not null auto_increment;

-- 创建带分区的表
CREATE TABLE `logs_withs_partitions` (
  `id` int NOT NULL AUTO_INCREMENT,
  `user_id` int NOT NULL,
  ...
  PRIMARY KEY (`id`,`user_id`)
) PARTITION BY HASH(user_id) PARTITIONS 5;
-- 将数据复制到带分区的表
insert into logs_withs_partitions
select * from logs;

-- 重命名表
rename table logs to logs_without_partitions;
rename table logs_withs_partitions to logs;

-- 删除不带分区的表
drop table logs_without_partitions;