您的位置:首页 > 数据库 > MySQL

MySQL分区表

2014-04-02 16:50 141 查看
MySQL对表进行分区时,作为分区的字段,必须在主键内。

如果不在主键字段内,会报下面错误;

A PRIMARY KEY must include all columns in the table's partitioning function。

MySQL官方文档是这么解释的:

18.5.1. Partitioning Keys, Primary Keys, and Unique Keys

This section discusses the relationship of partitioning keys with primary keys and unique keys. The rule governing this relationship can be expressed as follows: All columns used in the partitioning expression for a partitioned table must be part of every unique
key that the table may have.

In other words,every unique key on the table must use every columnin the table's partitioning expression. (This also includes the table's primary key, since it is by definition a unique key. This particular case is discussed later in this section.) For example,
each of the following table creation statements is invalid:

分区字段必须包含在主键字段内,至于为什么MYSQL会至于考虑,CSDN的版主是这么解释的:

为了确保主键的效率。否则同一主键区的东西一个A分区,一个在B分区,显然会比较麻烦。

解决一:

创建表的时候不建立主键

create table emp

(

id int(50) not null comment 'id',

name VARCHAR(50) comment '姓名',

creat_time DATETIME not null comment '创建时间'

)

engine=INNODB

partition by range(to_days(creat_time))

(

PARTITION p201404 VALUES LESS THAN (to_days('2014-04-01')) ,

PARTITION p201405 VALUES LESS THAN (to_days('2014-05-01')) ,

PARTITION p201406 VALUES LESS THAN (to_days('2014-06-01')) ,

PARTITION p202100 VALUES LESS THAN MAXVALUE

);

解决二:

创建表的时候建立复合主键,把分区字段加入主键内

create table emp

(

id int(50) not null comment 'id',

name VARCHAR(50) comment '姓名',

creat_time DATETIME not null comment '创建时间',

primary key (id,creat_time)

)

engine=INNODB

partition by range(to_days(creat_time))

(

PARTITION p201404 VALUES LESS THAN (to_days('2014-04-01')) ,

PARTITION p201405 VALUES LESS THAN (to_days('2014-05-01')) ,

PARTITION p201406 VALUES LESS THAN (to_days('2014-06-01')) ,

PARTITION p202100 VALUES LESS THAN MAXVALUE

);

最后结论,MySQL的分区字段,必须包含在主键字段内。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: