search
HomeDatabaseMysql TutorialMysql数据表分区技术PARTITION浅析_MySQL

在这一章节里, 我们来了解下 Mysql 中的分区技术 (RANGE, LIST, HASH)
 
Mysql 的分区技术与水平分表有点类似, 但是它是在逻辑层进行的水平分表, 对于应用而言它还是一张表, 换句话说: 分区不是实际真正的对一张表进行拆分,分区之后表还是一个表,它是把存储文件进行拆分。

在 Mysql 5.1(后) 有了几种分区类型:
 
RANGE分区: 基于属于一个给定连续区间的列值, 把多行分配给分区

LIST分区: 类似于按 RANGE 分区, 区别在于 LIST 分区是基于列值匹配一个离散值集合中的某个值来进行选择

HASH分区: 基于用户定义的表达式的返回值来进行选择分区, 该表达式使用将要插入到表中的这些行的列值进行计算, 这个函数可以包含 Mysql 中有效的、产生非负整数值的任何表达式

KEY分区: 累世于按 HASH 分区, 区别在于 KEY 分区只支持计算一列或多列, 且 Mysql 服务器提供其自身的哈希函数
 
分区应该注意的事项:

1、 做分区时,要么不定义主键,要么把分区字段加入到主键中
2、 分区字段不能为NULL,要不然怎么确定分区范围呢,所以尽量 NOT NULL
 
首先你可以查看下你的 Mysql 版本是否支持 PARTITION
复制代码 代码如下:
mysql> show plugins;
 
| partition    | ACTIVE   | STORAGE ENGINE     | NULL    | GPL     |

或者:
复制代码 代码如下:
mysql> show variables like "%part%";
 
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| have_partitioning | YES   |
+-------------------+-------+

RANGE 分区
 
假定你创建了一个如下的表, 该表保存有20家音像店的职员记录, 这20家音像店的编号从1到20。 如果你想将其分成4个小分区, 那么你可以采用RANGE分区, 创建的数据库表如下:
复制代码 代码如下:
mysql-> CREATE TABLE employees (
     ->     id INT NOT NULL,
     ->     fname VARCHAR(30),
     ->     lname VARCHAR(30),
     ->     hired DATE NOT NULL DEFAULT '1970-01-01',
     ->     separated DATE NOT NULL DEFAULT '9999-12-31',
     ->     job_code INT NOT NULL,
     ->     store_id INT NOT NULL
     -> ) ENGINE=Myisam DEFAULT CHARSET=utf8
     -> PARTITION BY RANGE (store_id) (
     ->     PARTITION P0 VALUES LESS THAN (6),
     ->     PARTITION P1 VALUES LESS THAN (11),
     ->     PARTITION P2 VALUES LESS THAN (16),
     ->     PARTITION P3 VALUES LESS THAN (21)
     -> );
如果你想把不同时期离职的员工进行分别存储, 那么你可以将日期字段 separated (即离职时间) 作为一个 key, 创建的 SQL 语句如下:
复制代码 代码如下:
mysql-> CREATE TABLE employees (
     ->     id INT NOT NULL,
     ->     fname VARCHAR(30),
     ->     lname VARCHAR(30),
     ->     hired DATE NOT NULL DEFAULT '1970-01-01',
     ->     separated DATE NOT NULL DEFAULT '9999-12-31',
     ->     job_code INT NOT NULL,
     ->     store_id INT NOT NULL
     -> ) ENGINE=Myisam DEFAULT CHARSET=utf8
     -> PARTITION BY RANGE (YEAR(separated)) (
     ->     PARTITION P0 VALUES LESS THAN (2001),
     ->     PARTITION P1 VALUES LESS THAN (2011),
     ->     PARTITION P2 VALUES LESS THAN (2021),
     ->     PARTITION P3 VALUES LESS THAN MAXVALUE
     -> );
 
List 分区
 
同样的例子, 如果这20家影像店分布在4个有经销权的地区,
复制代码 代码如下:
+------------------+--------------------------------------+
| 地区             | 音像店 ID 号                         |
+------------------+--------------------------------------+
| 北区             | 3, 5, 6, 9, 17                       |
| 东区             | 1, 2, 10, 11, 19, 20                 |
| 西区             | 4, 12, 13, 14, 18                    |
| 中心区           | 7, 8, 15, 16                         |
+------------------+--------------------------------------+
 
mysql-> CREATE TABLE employees (
     ->     id INT NOT NULL,
     ->     fname VARCHAR(30),
     ->     lname VARCHAR(30),
     ->     hired DATE NOT NULL DEFAULT '1970-01-01',
     ->     separated DATE NOT NULL DEFAULT '9999-12-31',
     ->     job_code INT NOT NULL,
     ->     store_id INT NOT NULL
     -> ) ENGINE=Myisam DEFAULT CHARSET=utf8
     -> PARTITION BY LIST (store_id) (
     ->     PARTITION pNorth   VALUES IN (3, 5, 6, 9, 17),
     ->     PARTITION pEast    VALUES IN (1, 2, 10, 11, 19, 20),
     ->     PARTITION pWest    VALUES IN (4, 12, 13, 14, 18),
     ->     PARTITION pCentral VALUES IN (7, 8, 15, 16)
     -> );


当你创建完之后, 你可以进入 Mysql 数据储存文件, 该文件夹位置定义在 Mysql 配置文件中
复制代码 代码如下:
shawn@Shawn:~$ sudo vi /etc/mysql/my.cnf;
 
[mysqld]
datadir         = /var/lib/mysql
 
shawn@Shawn:~$ cd /var/lib/mysql/dbName
shawn@Shawn:/var/lib/mysql/dbName$ ll
 
显示如下:
8768 Jun  7 22:01 employees.frm
  48 Jun  7 22:01 employees.par
   0 Jun  7 22:01 employees#P#pCentral.MYD
1024 Jun  7 22:01 employees#P#pCentral.MYI
   0 Jun  7 22:01 employees#P#pEast.MYD
1024 Jun  7 22:01 employees#P#pEast.MYI
   0 Jun  7 22:01 employees#P#pNorth.MYD
1024 Jun  7 22:01 employees#P#pNorth.MYI
   0 Jun  7 22:01 employees#P#pWest.MYD
1024 Jun  7 22:01 employees#P#pWest.MYI
从这里可以看出, 它是把存储文件根据我们的定义进行了拆分
复制代码 代码如下:
employees.frm = 表结构
employees.par = partition, 申明是一个分区表
.MYD = 数据文件
.MYI = 索引文件
 
HASH 分区
 
HASH 分区主要用来确保数据在预先确定数目的分区中平均分布
如果你想把不同时期加入的员工进行分别存储, 那么你可以将日期字段 hired 作为一个 key
复制代码 代码如下:
mysql-> CREATE TABLE employees (
     ->     id INT NOT NULL,
     ->     fname VARCHAR(30),
     ->     lname VARCHAR(30),
     ->     hired DATE NOT NULL DEFAULT '1970-01-01',
     ->     separated DATE NOT NULL DEFAULT '9999-12-31',
     ->     job_code INT NOT NULL,
     ->     store_id INT NOT NULL
     -> ) ENGINE=Myisam DEFAULT CHARSET=utf8
     -> PARTITION BY HASH (YEAR(hired)) (
     ->     PARTITIONS 4
     -> );
     
#这里注意的是 PARTITIONS, 多了一个 s
这里要提一下的就是, 如上的例子都是使用的是 Myisam 存储引擎,它默认使用独立表空间, 所以你可以在上面的磁盘空间里看到不同的分区
而 InnoDB 引擎则默认使用共享表空间, 此时就算你对 InnoDB 表进行分区, 你查看下会发现, 它并没有像 Myisam 那么样进行物理上的分区, 所以你需要修改下 Mysql 配置文件:
复制代码 代码如下:
shawn@Shawn:~$ sudo vi /etc/mysql/my.cnf;
 
#添加:
innodb_file_per_table=1
 
#重启 mysql
shawn@Shawn:~$ sudo /etc/init.d/mysql restart
此时你再对 InooDB 进行分区, 则会有如下效果:
复制代码 代码如下:
8768 Jun  7 22:54 employees.frm
   48 Jun  7 22:54 employees.par
98304 Jun  7 22:54 employees#P#pCentral.ibd
98304 Jun  7 22:54 employees#P#pEast.ibd
98304 Jun  7 22:54 employees#P#pNorth.ibd
98304 Jun  7 22:54 employees#P#pWest.ibd
分区管理
 
删除分区
复制代码 代码如下:
mysql> alter table employees drop partition pWest; 
新增分区
复制代码 代码如下:
#range添加新分区 
mysql> alter table employees add partition ( partition p4 values less than (26) ); 
  
#list添加新分区 
mysql> alter table employees add partition( partition pSouth values in (21, 22, 23) ); 
  
#hash重新分区 
mysql> alter table employees add partition partitions 5; 

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
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.