欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySql数据分区操作之新增分区操作

程序员文章站 2024-02-28 23:20:10
如果想在已经建好的表上进行分区,如果使用alter添加分区的话,mysql会提示错误: 复制代码 代码如下: error 1505 part...

如果想在已经建好的表上进行分区,如果使用alter添加分区的话,mysql会提示错误:

复制代码 代码如下:

error 1505 <hy000> partition management on a not partitioned table is not possible

正确的方法是新建一个具有分区的表,结构一致,然后用insert into 分区表 select * from 原始表;

测试创建分区表文件

复制代码 代码如下:

create table tr (id int, name varchar(50), purchased date)
partition by range(year(purchased))
(
    partition p0 values less than (1990),
    partition p1 values less than (1995),
    partition p2 values less than (2000),
    partition p3 values less than (2005)
);

插入测试数据

复制代码 代码如下:

insert into tr values
(1, 'desk organiser', '2003-10-15′),
(2, 'cd player', '1993-11-05′),
(3, 'tv set', '1996-03-10′),
(4, 'bookcase', '1982-01-10′),
(5, 'exercise bike', '2004-05-09′),
(6, 'sofa', '1987-06-05′),
(7, 'popcorn maker', '2001-11-22′),
(8, 'aquarium', '1992-08-04′),
(9, 'study desk', '1984-09-16′),
(10, 'lava lamp', '1998-12-25′);

查询p2中的数据

复制代码 代码如下:

select * from tr where purchased between '1995-01-01′ and '2004-12-31′;

如果删除p2,在删除p2分区的同时,也会将其下的所有数据删除

复制代码 代码如下:

alter table tr drop partition p2;
show create table tr;
create table `tr` (
  `id` int(11) default null,
  `name` varchar(50) default null,
  `purchased` date default null
) engine=myisam default charset=utf8
/*!50100 partition by range (year(purchased))
(partition p0 values less than (1990) engine = myisam,
 partition p1 values less than (1995) engine = myisam,
 partition p3 values less than (2005) engine = myisam) */
 

再次插入数据时,会将原p2的数据插入至p3中

复制代码 代码如下:

insert into tr values (11, 'pencil holder', '1995-07-12′);
alter table tr drop partition p3;
select * from tr where purchased  between '1995-01-01′ and '2004-12-31′;

创建一个新的测试表

复制代码 代码如下:

create table members (
    id int,
    fname varchar(25),
    lname varchar(25),
    dob date
)
partition by range(year(dob)) (
    partition p0 values less than (1970),
    partition p1 values less than (1980),
    partition p2 values less than (1990)
);

直接用alter table tablename add partition 方式再最后面添加分区

复制代码 代码如下:

alter table members add partition (partition p3 values less than (2000));

复制代码 代码如下:

alter table members reorganize partition p0 into (
    partition m0 values less than (1960),
    partition m1 values less than (1970)
);
show create table members;
create table `members` (
  `id` int(11) default null,
  `fname` varchar(25) default null,
  `lname` varchar(25) default null,
  `dob` date default null
) engine=myisam default charset=utf8
/*!50100 partition by range (year(dob))
(partition m0 values less than (1960) engine = myisam,
 partition m1 values less than (1970) engine = myisam,
 partition p1 values less than (1980) engine = myisam,
 partition p2 values less than (1990) engine = myisam,
 partition p3 values less than (2000) engine = myisam) */
 

使用 reorganize partition进行数据的合并与拆分,数据是没有丢失的。
(详细出处参考:)
如果用此方式在之前添加会报错,只能用另一种合并拆分分区的方式操作。