场景:
数据库中的某表的数据超过一千万,且是重要的业务表,页面查询下载卡顿;单表占用3G以上空间,试试分区能不能解决这个查询慢的问题。
select segment_name, bytes/1024/1024/1024
from user_segments
where segment_type = 'TABLE'
and SEGMENT_NAME = 'IB_TBS_STUDENTABSINFO';
一、对已有的表分区按天、周、月、年自动分区
查了一下,分区必须在建表的时候就指定好,如果后面再分,需要删除重建。
1、按年创建
numtoyminterval(1, ‘year’)
--按年创建分区表
create table test_part
(
ID NUMBER(20) not null,
REMARK VARCHAR2(1000),
create_time DATE
)
PARTITION BY RANGE (CREATE_TIME) INTERVAL (numtoyminterval(1, 'year'))
(partition part_t01 values less than(to_date('2018-11-01', 'yyyy-mm-dd')));
--创建主键
alter table test_part add constraint test_part_pk primary key (ID) using INDEX;
-- Create/Recreate indexes
create index test_part_create_time on TEST_PART (create_time);
2、按月创建
numtoyminterval(1, ‘month’)
--按月创建分区表
create table test_part
(
ID NUMBER(20) not null,
REMARK VARCHAR2(1000),
create_time DATE
)
PARTITION BY RANGE (CREATE_TIME) INTERVAL (numtoyminterval(1, 'month'))
(partition part_t01 values less than(to_date('2018-11-01', 'yyyy-mm-dd')));
--创建主键
alter table test_part add constraint test_part_pk primary key (ID) using INDEX;
3、按天创建
NUMTODSINTERVAL(1, ‘day’)
--按天创建分区表
create table test_part
(
ID NUMBER(20) not null,
REMARK VARCHAR2(1000),
create_time DATE
)
PARTITION BY RANGE (CREATE_TIME) INTERVAL (NUMTODSINTERVAL(1, 'day'))
(partition part_t01 values less than(to_date('2018-11-12', 'yyyy-mm-dd')));
--创建主键
alter table test_part add constraint test_part_pk primary key (ID) using INDEX;
4、按周创建
NUMTODSINTERVAL (7, ‘day’)
--按周创建分区表
create table test_part
(
ID NUMBER(20) not null,
REMARK VARCHAR2(1000),
create_time DATE
)
PARTITION BY RANGE (CREATE_TIME) INTERVAL (NUMTODSINTERVAL (7, 'day'))
(partition part_t01 values less than(to_date('2018-11-12', 'yyyy-mm-dd')));
--创建主键
alter table test_part add constraint test_part_pk primary key (ID) using INDEX;
5、测试
可以添加几条数据来看看效果,oracle 会自动添加分区。
--查询当前表有多少分区
select table_name,partition_name from user_tab_partitions where table_name='TEST_PART';
--查询这个表的某个(SYS_P21)里的数据
select * from TEST_PART partition(SYS_P21);
参考链接:
https://www.cnblogs.com/yuxiaole/p/9809294.html