MySQL优化_合并表和分区表

一、合并表和分区表php

1.一、合并表:把多个结果相同的表合并成为一个容器。sql

表类型:Myisam   存储引擎:merge数据库

合并:unionless

Create table packtable (数据库设计

Id int not null primary key函数

) engine=merge union=(table1,table2)spa

存在的问题:有重复的行设计

 

 

临时表(内存临时表、磁盘临时表):索引

使用场景:内存

有大量的数据表的关联查询;

可以在数据量大的表中筛选记录;

处理数据只须要某一些符合条件的数据;

数据会被很快销毁的场景。

使用临时表:

  select查询中指定sql_small_result

Order by 使用了dinstinct

使用Join查询的时候,若是group by的列不是第一个表的列  

 

直接使用磁盘临时表:

Text类型、blob类型;

Groupby、ditinct子句中大于512byte的列

Union、union all,select子句大于512byte的列

临时表的配置:

Tmp_table-size   系统建立    max_heap_table_size 用户建立的

怎么避免临时表:

建立索引:在group by、order by的列建立索引;

拆分列、text字段通常单独放在另外一张表或者不放在查询条件里;

建立临时表:

CREATE TEMPORARY TABLE test1 {

Id int(10) not null,

Username varchar(50)

}

注意:php脚本中建立临时表,临时表只对当前链接可见,脚本执行完毕,临时表自动销毁;

客户端链接:须要关闭客户端;

手动删除临时表:drop table test1;

 

问题1: 如何合并两张表?

Union   自动去重    select * from test1 union select * from test2;

union all       不会去重,字段数量、类型必须相同

问题2:a表和b表合并(使用临时表)?

CREATE TEMPORARY TABLE test1 {

Id int(10) not null,

Username varchar(50)

}

Insert into test1 select * from test1 union select * from test2;

=========================================

CREATE TEMPORARY TABLE test2 SELECT * from test1;

业务处理

问题3:a表和b表合并到c表,数据量大的状况

A表、 B表数据插入临时表;

在临时表/中间表中建立联合索引;

Create index union_a on test1 ( c1,c2,c3);

 

 

 

1.二、分区表(partition):建立分区表的每一个分区都是有索引的独立表

目的:物理数据库设计技术、让某些特定的查询减小响应时间

分区类型:水平分区、垂直分区

水平分区:

RANGE分区:连续的空间   range values less than

Create table test1 (

Id int(10) not null,

Score int(3),

)  partition by range(score)(

partition p1 values less than(60),

partition p2 values less than(80),

 

partition p3 values less than maxvalue

);

Insert into test1 values(1,50);

Select count(*) from test1 where score <60;

 

LIST分区:定义和选择是基于某一列的值是否属于某一个集合。

Mysql>=5.5  集合的值支持非整型数据

Create table test1 (

Id int(10) not null,

Score int(3),

)  partition by list(dept_no)(

partition p1 values in(3,8),

partition p2 values in(7),

);

 

HASH分区(只支持数值类型):

Create table test1 (

Id int(10) not null,

Score int(3),

Birthday date

)  partition by hash(month(Birthday))

 Partitions 12;

Mode(6,12) //6   哈希函数的取余

 

线性hash分区: //2的幂运算

Create table test1 (

Id int(10) not null,

Score int(3),

Birthday date

)  partition by linear hash( month(Birthday) )

V=POW(2,ceiling(LOG(2,num)));  计算N

 Partitions 12;

线性HASH分区的好处:当数据量大于1000G的时候,对分区的增长、合并、拆分、删除会变得更加快捷。

线性HASH分区的缺点:数据分布不均匀。

 

KEY分区(只计算一列或者多列):支持除了text和blob之外的其余类型

Create table test1 (

Id int(10) not null,

Score int(3),

Birthday date,

Course varchar(25)

)  partition by key( course )

 Partitions 5;

 

复合分区:

相关文章
相关标签/搜索