MySQL單表數據量彩掐,建議不要超過2000W行,否則會對性能有較大影響枫匾。最近接手了一個項目架诞,單表數據超7000W行,一條簡單的查詢語句等了50多分鐘都沒出結果干茉,實在是難受谴忧,最終,我們決定用分區(qū)表角虫。
建表
一般的表(innodb)創(chuàng)建后只有一個 idb 文件:
create table normal_table(id int primary key, no int)
查看數據庫文件:
normal_table.ibd
創(chuàng)建按月份分區(qū)的分區(qū)表沾谓,注意!除了常規(guī)主鍵外戳鹅,月份字段(用來分區(qū)的字段)也必須是主鍵:
create table partition_table(id int AUTO_INCREMENT, create_date date, name varchar(10),
primary key(id, create_date)) ENGINE=INNODB DEFAULT CHARSET=utf8
partition by range(month(create_date))(
partition quarter1 values less than(4),
partition quarter2 values less than(7),
partition quarter3 values less than(10),
partition quarter4 values less than(13)
);
查看數據庫文件:
partition_table#p#quarter1.ibd
partition_table#p#quarter2.ibd
partition_table#p#quarter3.ibd
partition_table#p#quarter4.ibd
插入
insert into partition_table(create_date, name) values("2021-01-25", "tom1");
insert into partition_table(create_date, name) values("2021-02-25", "tom2");
insert into partition_table(create_date, name) values("2021-03-25", "tom3");
insert into partition_table(create_date, name) values("2021-04-25", "tom4");
insert into partition_table(create_date, name) values("2021-05-25", "tom5");
insert into partition_table(create_date, name) values("2021-06-25", "tom6");
insert into partition_table(create_date, name) values("2021-07-25", "tom7");
insert into partition_table(create_date, name) values("2021-08-25", "tom8");
insert into partition_table(create_date, name) values("2021-09-25", "tom9");
insert into partition_table(create_date, name) values("2021-10-25", "tom10");
insert into partition_table(create_date, name) values("2021-11-25", "tom11");
insert into partition_table(create_date, name) values("2021-12-25", "tom12");
查詢
select count(*) from partition_table;
> 12
查詢第二個分區(qū)(第二季度)的數據:
select * from partition_table PARTITION(quarter2);
4 2021-04-25 tom4
5 2021-05-25 tom5
6 2021-06-25 tom6
刪除
當刪除表時均驶,該表的所有分區(qū)文件都會被刪除