指标:执行时间 检查的行数 返回的行数

1. count的优化

比如:计算id大于5的城市 a. select count(*) from world.city where id > 5; b. select (select count(*) from world.city) – count(*) from world.city where id <= 5; a语句当行数超过11行的时候需要扫描的行数比b语句要多, b语句扫描了6行,此种情况下,b语句比a语句更有效率。当没有where语句的时候直接select count(*) from world.city这样会更快,因为mysql总是知道表的行数。

案例:

# 建库
create database if not exists db3 default charset=utf8;
use db3;
# 建表
create table if not exists cnt(id int , name varchar(10),age int ,tel varchar(10));
# 创建存储过程 procedrue  
delimiter $
create procedure cnt()
begin
#定义变量 declare
declare i int default 0;
while(i<100000) do
    begin
        select i;
        set i=i+1;
        insert into cnt(id,name)values(i,'zs');
    end;
end while;
end $
delimiter ;
#调用存储过程
call cnt();

    
select count(*)from cnt;
#执行耗时   : 0 sec 传送时间   : 0.051 sec 总耗时      : 0.051 sec
#数据库知道表内有多少条数据    

select count(*) from cnt where id > 5;  
# 执行耗时   : 0.130 sec 传送时间   : 0 sec 总耗时      : 0.130 sec
# 使用where 扫描了全表 id > 5的所有数据 总查询99995条

select (select count(*) from cnt) - count(*) from cnt where id <=5 ;
# 执行耗时   : 0.080 sec 传送时间   : 0 sec  总耗时      : 0.081 sec
# 使用where 扫描全表 id <= 5 的五条数据  加上 (select count(*) from cnt) 一条数据 总查询 6 条

2. 避免使用不兼容的数据类型。

例如float和int、char和varchar、binary和varbinary是不兼容的。数据类型的不兼容可能使优化器无法执行一些本来可以进行的优化操作。 在程序中,保证在实现功能的基础上,尽量减少对数据库的访问次数;通过搜索参数,尽量减少对表的访问行数,最小化结果集,从而减轻网络负担;

能够分开的操作尽量分开处理,提高每次的响应速度;

在数据窗口使用sql时,尽量把使用的索引放在选择的首列;算法的结构尽量简单;在查询时,不要过多地使用通配符如 select * from t1语句,要用到几列就选择几列如:select col1,col2 from t1;

在可能的情况下尽量限制尽量结果集行数如:select top 300 col1,col2,col3 from t1,因为某些情况下用户是不需要那么多的数据的。不要在应用中使用数据库游标,游标是非常有用的工具,但比使用常规的、面向集的sql语句需要更大的开销;按照特定顺序提取数据的查找。

案例:

# 创建一个表测试了一下 int 类型数据插入float类型的数据  结果:插入数度变慢 会四舍五入
create table sss(id int);
insert into sss values(12.4);
insert into sss values(12.5);

3. 索引字段上进行运算会使索引失效。

尽量避免在where子句中对字段进行函数或表达式操作,这将导致引擎放弃使用索引而进行全表扫描。

如:select * from t1 where f1/2=100 应改为: select * from t1 where f1=100*2

案例:

#创建索引
create index index_id on cnt(id);

select * from cnt where id > 50000;
#行耗时   : 0.009 sec  传送时间   : 0 sec  总耗时      : 0.010 sec
select * from cnt where id*2 > 100000;
#执行耗时   : 0.031 sec 传送时间   : 0 sec  总耗时      : 0.032 sec
# 使用了索引进行运算  使得索引失效 效率变慢了

4. 避免使用!=或<>、is null或is not null、in ,not in等这样的操作符.

因为这会使系统无法使用索引,而只能直接搜索表中的数据。例如: select id from employee where id != “b%” 优化器将无法通过索引来确定将要命中的行数,因此需要搜索该表的所有行。在in语句中能用exists语句代替的就用exists.

5. 尽量使用数字型字段.

一部分开发人员和数据库管理人员喜欢把包含数值信息的字段 设计为字符型,这会降低查询和连接的性能,并会增加存储开销。这是因为引擎在处理查询和连接回逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。

6. 合理使用exists,not exists子句。如下所示:

select sum(t1.c1) from t1 where (select count(*)from t2 where t2.c2=t1.c2>0) 2.select sum(t1.c1) from t1where exists(select * from t2 where t2.c2=t1.c2) 两者产生相同的结果,但是后者的效率显然要高于前者。

因为后者不会产生大量锁定的表扫描或是索引扫描。如果你想校验表里是否存在某条纪录,不要用count(*)那样效率很低,而且浪费服务器资源。可以用exists代替。如:if (select count(*) from table_name where column_name = ‘xxx’)

可以写成:if exists (select * from table_name where column_name = ‘xxx’)

7. 能够用between的就不要用in

8. 能够用distinct的就不用group by

9. 尽量不要用select into语句。

select into 语句会导致表锁定,阻止其他用户访问该表。

10. 必要时强制查询优化器使用某个索引

select * from t1 where nextprocess = 1 and processid in (8,32,45)

改成: select * from t1 (index = ix_processid) where nextprocess = 1 and processid in (8,32,45)

则查询优化器将会强行利用索引ix_processid 执行查询。

案例:

# 10.必要时强制查询优化器使用索引
#建表
create table if not exists t1(processid int, nextprocess int);
#建索引
create index index_processid on t1(processid);
# 10.1:不使用索引
select * from t1 where nextprocess = 1 and processid in (8,32,45);
# 10.2: 强制使用索引
select * from t1 froce index(index_processid)
 where nextprocess = 1 and process = 1 and processid in (8,32,45);

11. 消除对大型表行数据的顺序存取

尽管在所有的检查列上都有索引,但某些形式的where子句强迫优化器使用顺序存取。如: select * from orders where (customer_num=104 and order_num>1001) or order_num=1008 解决办法可以使用并集来避免顺序存取: select * from orders where customer_num=104 and order_num>1001 union select * from orders where order_num=1008 这样就能利用索引路径处理查询。【jacking 数据结果集很多,但查询条件限定后结果集不大的情况下,后面的语句快】

案例:

# 11.消除对大型表 行数据的顺序存取
#建表
create table if not exists orders(customer_num int, order_num int);
# 消除顺序索引
#11.1 没有使用索引
select * from orders where (customer_num=104 and order_num > 100) or order_num=1005;
#11.2 使用索引  将or 拆开 避免使用or
select * from orders where custoner_num = 104 and order_num > 100
union  # union 默认去重,排序   union all 不去重,不会排序 
select * from orders where order_num=1005;

12. 尽量避免在索引过的字符数据中,使用非打头字母搜索。这也使得引擎无法利用索引。

见如下例子: select * from t1 where name like ‘%l%’ select * from t1 where substing(name,2,1)=’l’ select * from t1 where name like ‘l%’ 即使name字段建有索引,前两个查询依然无法利用索引完成加快操作,引擎不得不对全表所有数据逐条操作来完成任务。而第三个查询能够使用索引来加快操作,不要习惯性的使用 ‘%l%’这种方式(会导致全表扫描),如果可以使用`l%’相对来说更好;

 案例:

# 12. 模糊查询where like ,字母打头'1%' 会使用索引 即%在右
create table if not exists t2(name varchar(20));
create index  index_name on t2(name);
# 12.1 不会使用索引
select * from t2 where name like '%l%';
select * from t2 where name like '%l';
    #substring 进行字符串截取 参数:字符串,起始位置,结束位置
select * from t2 where substring(name,2,1)='l'; 
# 12.2 使用到索引
select * from t2 where name like 'l%';

13. 虽然update、delete语句的写法基本固定,但是还是对update语句给点建议:

a) 尽量不要修改主键字段。 b) 当修改varchar型字段时,尽量使用相同长度内容的值代替。 c) 尽量最小化对于含有update触发器的表的update操作。 d) 避免update将要复制到其他数据库的列。 e) 避免update建有很多索引的列。 f) 避免update在where子句条件中的列。

14. 能用union all就不要用union

union all不执行select distinct函数,这样就会减少很多不必要的资源 在跨多个不同的数据库时使用union是一个有趣的优化方法,union从两个互不关联的表中返回数据,这就意味着不会出现重复的行,同时也必须对数据进行排序,我们知道排序是非常耗费资源的,特别是对大表的排序。 union all可以大大加快速度,如果你已经知道你的数据不会包括重复行,或者你不在乎是否会出现重复的行,在这两种情况下使用union all更适合。此外,还可以在应用程序逻辑中采用某些方法避免出现重复的行,这样union all和union返回的结果都是一样的,但union all不会进行排序。

15. 字段数据类型优化:

a. 避免使用null类型:null对于大多数数据库都需要特殊处理,mysql也不例外,它需要更多的代码,更多的检查和特殊的索引逻辑,有些开发人员完全没有意识到,创建表时null是默认值,但大多数时候应该使用not null,或者使用一个特殊的值,如0,-1作为默认值。 b. 尽可能使用更小的字段,mysql从磁盘读取数据后是存储到内存中的,然后使用cpu周期和磁盘i/o读取它,这意味着越小的数据类型占用的空间越小,从磁盘读或打包到内存的效率都更好,但也不要太过执着减小数据类型,要是以后应用程序发生什么变化就没有空间了。修改表将需要重构,间接地可能引起代码的改变,这是很头疼的问题,因此需要找到一个平衡点。 c. 优先使用定长型

16. 关于大数据量limit分布的优化见下面链接(当偏移量特别大时,limit效率会非常低):

http://ariyue.iteye.com/blog/553541 附上一个提高limit效率的简单技巧,在覆盖索引(覆盖索引用通俗的话讲就是在select的时候只用去读取索引而取得数据,无需进行二次select相关表)上进行偏移,而不是对全行数据进行偏移。可以将从覆盖索引上提取出来的数据和全行数据进行联接,然后取得需要的列,会更有效率,看看下面的查询: mysql> select film_id, description from sakila.film order by title limit 50, 5; 如果表非常大,这个查询最好写成下面的样子: mysql> select film.film_id, film.description from sakila.film inner join(select film_id from sakila.film order by title liimit 50,5) as film usinig(film_id);

17. 程序中如果一次性对同一个表插入多条数据,比如以下语句:

insert into person(name,age) values(‘xboy’, 14); insert into person(name,age) values(‘xgirl’, 15); insert into person(name,age) values(‘nia’, 19); 把它拼成一条语句执行效率会更高. insert into person(name,age) values(‘xboy’, 14), (‘xgirl’, 15),(‘nia’, 19);

18. 不要在选择的栏位上放置索引,这是无意义的。

应该在条件选择的语句上合理的放置索引,比如where,order by。

select id,title,content,cat_id from article where cat_id = 1;

19. order by语句的mysql优化:

a. order by + limit组合的索引优化。

如果一个sql语句形如:

select [column1],[column2],…. from [table] order by [sort] limit [offset],[limit];

这个sql语句优化比较简单,在[sort]这个栏位上建立索引即可。

b. where + order by + limit组合的索引优化,形如:

select [column1],[column2],…. from [table] where [columnx] = [value] order by [sort] limit [offset],[limit];

这个语句,如果你仍然采用第一个例子中建立索引的方法,虽然可以用到索引,但是效率不高。更高效的方法是建立一个联合索引(columnx,sort)

c. where + in + order by + limit组合的索引优化,形如:

select [column1],[column2],…. from [table] where [columnx] in ([value1],[value2],…) order by [sort] limit [offset],[limit];

这个语句如果你采用第二个例子中建立索引的方法,会得不到预期的效果(仅在[sort]上是using index,where那里是using where;using filesort),理由是这里对应columnx的值对应多个。 目前哥还木有找到比较优秀的办法,等待高手指教。

d.where+order by多个栏位+limit,比如:

select * from [table] where uid=1 order x,y limit 0,10;

对于这个语句,大家可能是加一个这样的索引:(x,y,uid)。但实际上更好的效果是(uid,x,y)。这是由mysql处理排序的机制造成的。

总结

到此这篇关于mysql查询优化的一些实用方法的文章就介绍到这了,更多相关mysql查询优化内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!