SQL优化

来源:互联网 发布:linux内存管理详解 编辑:程序博客网 时间:2024/05/17 01:25

优化SQL语句的一般问题

1.show  [session | global ] status like '%string%'  了解服务器状态信息。例如com_select : 执行select操作的次数

2. explain select 链接服务器如何执行select语句以及执行过程中如何连接。输出结构中的type字段表示MySQL在表中找到所需行的方式。其类型有如下几种:

all:全表扫描,遍历全表来找到匹配行 。     例子:explain select * froim film where ration>9 (注释:rating字段上无索引 )

index:索引全扫描,遍历整个索引来查询匹配的行。  例子:explain select title from film (注释:title字段上有索引)

range:索引范围扫描,常见于<,<=等操作符 。    例子:explain select * from payment where customer_id>=300 and customer_id<=350;(注释:customer_id字段上有索引)

ref:使用非唯一索引扫描或者唯一索引的前缀扫描,返回匹配某个单独值的记录行。  例子:explain select * from payment where customer_id=350;(注释:customer_id字段上有索引)

eq_ref:使用的索引是唯一索引,对于每个索引键值,表中只有一条记录匹配。   例子:explain select * from film a,film_text b where a.film_id=b.film_id;(注释:customer_id字段上有索引)

const/system:表单中最多一个匹配行,例如primary key和unique index.

null:不用访问就可以得到结果。  例子:select 1 from dual .

备注:1.类型type还有其他的取值:ref_or_null   ,   index_merge  ,   unique_subquery  ,   index_sunquer。2.开始执行explain extended命令,在执行show warnings命令,我们能够看到SQL优化之前优化器做了哪些改进。3.explain partition  select 可以查看select所访问的分区

3.show profiles:查看已经执行的SQL语句

   show profile for query n :查看query  n线程的每个状态和消耗的时间。

索引问题

1.使用索引的典型场景

匹配全值:对某个索引中的所有列都指定具体指。

匹配值的范围查询:对索引值能够进行范围查找。

匹配最前缀:仅仅使用某个符合索引的最左边列进行查找。

仅仅对索引进行查询:查询的列都在索引的字段中。

匹配列前缀.

能够实现索引匹配部分精确而其他部分进行范围匹配。

列名是索引






1 0
原创粉丝点击