Home  >  Article  >  Database  >  【MYSQL】 分区表

【MYSQL】 分区表

WBOY
WBOYOriginal
2016-06-07 16:43:12942browse

对于MYSQL的态度一直都是会基本SQL和简单命令就行,最近处理一个数据量很大的项目,为了提高效率,在数据库方面的瓶颈上,选择了使用分区表来提高查询效率。至此

    对于MYSQL的态度一直都是会基本SQL和简单命令就行,最近处理一个数据量很大的项目,为了提高效率,在数据库方面的瓶颈上,选择了使用分区表来提高查询效率。至此和大家一起分享一下。

    1.引言

    本文初略的讲述了mysql数据库如何分区表。

    

    2.环境要求

    在5.1版本中不是默认就安装了,而在之后版本中一般默认选择了安装分区表支持。可以通过如下方式查看当前数据库是否支持分区表操作:

wKioL1R6ym7A0CplAABfWiOHn-I850.jpg

    使用show variables like '%partition%';如果不支持分区,那么value字段值为No。


    3.重要概念描述

    3.1 分区字段

    1)当仅存在单一主键时,不存在唯一键,那么分区字段必须是主键字段;

    2)当存在复合主键时,不存在唯一键,那么分区字段必须是主键组合的一部分字段,一个或多个。

    3)当主键和唯一键都存在时,那么分区字段必须同时包括主键字段和唯一键字段。


    4.分区表类型

    4.1 range分区

    1)语法展示:

# 语法 # 在创建表单的最后,添加partitions by range(分区字段)( #   partition 分区名 values less than(阀值1), #   partition 分区名 values less than(阀值2), #   ... #   partition 分区名 values less than(阀值n), # )

    示例展示:

create table test_range( id int auto_increment, description varchar(50), primary key(id) ) ENGINE=InnoDB auto_increment=1 default charset=utf8 partition by range(id)( partition p1 values less than(6), #id    查看分区情况:   show create table test_range;

    

wKioL1R6z4qC137DAADITZNS8H8149.jpg

    

    注意到,在显示的表结构添加了分区表的信息。

    数据测试:

    insert into test_range values(null, "test1");         insert into test_range values(null, "test2");     insert into test_range values(null, "test3");     insert into test_range values(null, "test4");     insert into test_range values(null, "test5");     insert into test_range values(null, "test6");     insert into test_range values(null, "test7");     insert into test_range values(null, "test8");     insert into test_range values(null, "test9");     insert into test_range values(null, "test10");

    插入10条数据,此时我们来查看其查询执行过程:

wKioL1R60LDBET1bAADRpczcpSo931.jpg

    从结果可以发现,其只是在p1分区执行的查询,那么此时就减少了查询扫描的数据量,从而提高了查询效率。

    如果此时,我们插入第11条数据会发生什么情况呢?

   insert into test_range values(null, "test11");    会发错:insert into test_range values(null, "test11") Error Code: 1526. Table has no partition for value 11 0.015 sec

    原因很简单,因为在我们创建表单时,仅仅指定了1 - 10的id数值分区,当插入id=11时的分区时,此时没有分区提供,那么就引发错误,那么如果解决这样的问题呢,采取如下方式,修改表的分区方式:

alter table test_range add partition( partition p3 values less than(MAXVALUE) ); # 添加一个分区,也就是p3是id从11到maxValue的存放区域

    此时插入id=11的数据,并执行查询解析:

wKiom1R60nnwSlUUAADL0geAo20618.jpg

    发现,已经将其分配到p3分区中了。

    还需要特别注意的时,使用partition by range(分区字段),其中的分区字段可以是分区字段的表单式,但是必须是返回的整数,在5.5版本中,可以使用partition by range column/columns语法,指定某个字段。这里不做介绍。大家可以自己尝试一下。


    4.2 list分区

    list分区可以理解为集合分区方式,意思就是指定某个集合来分区。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn