MySQL分区

KEY算法

创建分区

create table 表名{
	字段 类型 ....
} partition by key(字段/表达式) partitions 分区数名

MySQL8已经不支持 MYISAM 引擎创建分区了

create table t5(
	id int not null auto_increment,
	username varchar(30) not null default '',
	primary key(id)
) engine = MYISAM partition by key(id) partitions 2
-- 报错
1178 - The storage engine for the table doesn't support native partitioning
-- 使用innodb引擎 创建二个分区
create table t1(
	id int not null auto_increment,
	username varchar(30) not null default '',
	primary key(id)
)partition by key(id) partitions 2
-- 此为根据id创建分区
-- 注:有主键和唯一键,分区字段必须要包含主键和唯一键

插入数据时,是根据mysql自身算法选择将数据插入到其对应的一个分区文件中
image
数据表对外只是显示一个数据表

修改分区

  • 语法

    alter table 表名 partition by key(字段) partitions 数量;
    
alter table t2 partition by key(id) partitions 6;

image

删除分区

  • 语法

    alter table 表名 coalesce partition 删除分区的数量
    
alter table t2 coalesce partition 2

image

hash算法

创建分区

create table 表名{
	字段 类型 ....
} partition by hash(字段/表达式) partitions 分区数名
create table t_hash(
	id int not null,
	username varchar(30) not null default '',
	primary key(id)
)partition by hash(id) partitions 2

image

修改分区

  • 语法

    alter table 表名 partition by hash(字段) partitions 数量;
    
alter table t_hash partition by hash(id) partitions 4

删除分区

  • 语法

    alter table 表名 coalesce partition 删除分区的数量
    
alter table t_hash coalesce partition 2

range算法

range表示区间,某个字段所对应的值在某个区间,就把这个数据放入这个区间所对应的分区文件中

创建分区

create table 表名(
	字段 类型 ....
)
partition by range(字段/表达式)(
	partition 名称1 values less than (常量),
	partition 名称2 values less than (常量)
)
create table t_range(
	id int not null auto_increment,
	username varchar(30) not null default '',
	iyear int not null default 0,
	primary key(id,iyear)
)
partition by range(iyear) (
	partition year90 values less than(2000),
	partition year00 values less than(2010)
)
-- 如果iyear字段的值小于2000,则将插入到year90的文件中
-- 注:如果iyear字段的值大于或等于2010,则插入失败;因为没有建立大于或等于2010的分区

image

追加分区

  • 语法

    alter table 表名 add partition (
    	partition 名称 values less than(常量)
    )
    -- 向后追加,不要向前追加
    
alter table t_range add partition (
	partition n3 values less than(2020)
)
-- 2020大于2010

image

删除分区

  • 语法

    alter table 表名 drop partition 分区名称
    

    分区内数据可能会丢失

alter table t_range drop partition n3

image

list算法

list表示集合,某个字段所对应的值在某个集合[列表],就把这个数据放入这个集合所对应的分区文件中

创建分区

create table 表名(
	字段 类型 ....
)
partition by list(字段/表达式)(
	partition 名称1 values in (列表),
	partition 名称2 values in (列表)
)
create table t_list(
	username varchar(30) not null default '',
	mouth int not null default 1
)
partition by list(mouth) (
	partition m1 values in (1,2,3,4),
	partition m2 values in (5,7,8,9)
)
-- 将数据放入对应集合的文件中

image

追加分区

  • 语法

    alter table 表名 add partition (
    	partition 名称 values in (列表)
    )
    
alter table t_list add partition (
	partition m3 values in (10,11,12)
)

image

删除分区

  • 语法

    alter table 表名 drop partition 分区名称
    

    分区内数据可能会丢失

alter table t_list drop partition m2

image


版权声明:本文为LIKEWWZ原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。