概述
不过使用表分区有个前提就是你的数据库必须支持. 那么,怎么知道我的数据库是否支持表分区呢?
执行命名 mysql> show plugins:
在返回的数据里面找到partition开头的信息,如下:
partition | ACTIVE | STORAGE ENGINE | NULL | GPL
如果后面partition跟的是ACTIVE则表示可以的.
数据库的表分区一般有两种方式:水平和垂直
-水平分区是将表的数据按行分割成不同的数据文件;
-垂直分区是将表的数据按列分割成不同的数据文件;
示例1:
1.创建表格,并进行分区.
注意下面这段代码是一个整体,只有结尾有一个分号(;).
create table userinfo(
user_id int primary key auto_increment,
user_name varchar(20) not null default 'apollo'
)
partition by range(user_id)(
partition p1 values less than (10),
partition p2 values less than (20),
partition p3 values less than maxvalue
);
2.给新建的表格插入数据
insert into userinfo values(3,'apollo');
insert into userinfo values(13,'jack');
insert into userinfo values(23,'merry');
3.查询每个分区的数据
select * from userinfo partition(p1);
select * from userinfo partition(p2);
select * from userinfo partition(p3);
示例2:
1.创建表格,并进行分区.
注意下面这段代码是一个整体,只有结尾有一个分号(;).
create table if not exists staffinfo(
id int(11) not null auto_increment comment '用户ID',
name varchar(50) not null default '' comment '名称',
gender int(1) not null default '0' comment '0为男,1为女',
primary key (id)
) engine=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1
PARTITION BY RANGE (id) (
PARTITION p0 VALUES LESS THAN (5),
PARTITION p1 VALUES LESS THAN (10),
PARTITION p2 VALUES LESS THAN (15),
PARTITION p3 VALUES LESS THAN (20),
PARTITION p4 VALUES LESS THAN MAXVALUE
);
2.给新建的表格插入数据
insert into staffinfo (null,'Ian',0);
insert into staffinfo (null,'Idell',0);
insert into staffinfo (null,'Jack',0);
insert into staffinfo (null,'Jackie',0);
insert into staffinfo (id,name,gender)values
(null,'Amour',1),
(null,'Ampere',0),
(null,'Amphlet',0),
(null,'Amphlett',0);
insert into staffinfo values
(null,'Baade',0),
(null,'Bab',0),
(null,'Baitson',1),
(null,'Bairnsfather',0);
insert into staffinfo (name,gender)values
('Cahill',1),
('Dagmar',0),
('Earl',0),
('Fabian',1);
insert into staffinfo (name,gender)values
('Gabriel',1),
('Hackett',0),
('Hahn',0),
('Hailey',0);
insert into staffinfo (name,gender)values
('Kaley',1),
('Lacey',0),
('Lake',0),
('Nadine',0),
('Oakes',0),
('Queenie',0),
('Sabina',0),
('Tabitha',0),
('Ulysses',0),
('Valentin',0),
('Waddell',0),
('Xavier',0),
('Yarbrough',0),
('Mabel',0);
3.查询id字段的个数
mysql> select count(id) as count from staffinfo;
+-------+
| count |
+-------+
| 13 |
+-------+
1 row in set (0.00 sec)
4.查询每个分区的数据
select * from staffinfo partition(p1);
select * from staffinfo partition(p2);
select * from staffinfo partition(p3);
select * from staffinfo partition(p4);
select * from staffinfo partition(p5);
5.删除分区4的数据
alter table staffinfo drop partition p4;
总结:
分区的最小区块是4K
ENGINE=MyISAM: 使用MyISAM引擎
DEFAULT CHARSET=utf8: 数据库默认编码为utf-8
AUTO_INCREMENT=1: 自增键的起始序号为1