查看数据库版本是否支持分区:


mysql分区_第1张图片

分区的四种类型:

  1. Range分区(范围分区,根据某个字段的值来进行分区,某个连续的区间来进行区分):

创建表时分区

create table teacher
(id varchar(20) not null ,
name varchar(20),
age varchar(20),
birthdate date not null,
salary int
)
partition by range(year(birthdate))
(
partition p1 values less than (1970),
partition p2 values less than (1990),
partition p3 values less than maxvalue
);

创建表后分区:

ALTER TABLE teacher 
partition by range(year(birthdate))
(
partition p1 values less than (1970),
partition p2 values less than (1990),
partition p3 values less than maxvalue
);

2.LIST分区(和range分区差不多,只不过range是连续的,而list是分布的散列值):

create table student (
    id varchar(20) not null , 
    studentno int(20) not null, 
    name varchar(20), 
    age varchar(20) ) 
partition by list(studentno) 
(partition p1 values in (1,2,3,4), 
 partition p2 values in  (5,6,7,8), 
 partition p3 values in (9,10,11) );

Ps:如上创建表student,并将student表分为p1、p2、p3三个分区。需要注意的是一般情况下,针对表的分区字段为int等数值类型。

3.HASH分区(哈希分区主要是依据表的某个字段以及指定分区的数量。

create table user (  
    id int(20) not null,  
    role varchar(20) not null,  
    description varchar(50) )
partition by hash(id) partitions 10;

Ps:如上创建user表,并将user表平均分为十个分区。比较有限制的就是需要知道表的数据有多少才能更好平均分配分区。

4.KEY分区(类似于按HASH分区,区别在于KEY分区只支持计算一列或多列,且MySQL服务器提供其自身的哈希函数。必须有一列或多列包含整数值。)

create table role( 
    id int(20) not null,
    name varchar(20) not null)
partition by linear key(id)partitions 10;

5、分区管理:

5.1)对指定表添加分区

alter table user add partition(partition p4 values less than MAXVALUE);

5.2)删除指定表指定分区

alter table student drop partition p1;

5.3)创建子分区

create table role_subp(id int(20) not null,name int(20) not null)
partition by list(id)
subpartition by hash(name)
subpartitions 3
(
  partition p1 values in(10),
  partition p2 values in(20)
)

5.4)复合分区

alter table user
reorganize partition p1,p3 into
(partition p1 values less than (1000));