数据库的SQL优化

1.对查询进行优化,要尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。

(因为在条件查询条件添加索引,会直接被检索到列,会非常的快速)

 

2.应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描

最好不要给数据库留NULL,尽可能的使用 NOT NULL填充数据库.

例如:

 1 select id from t where num is null 

可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:

 1 select id from t where num = 0 

 

3.不要使用

 1 sleect * from name 

(这个绝对的全部的查询,千万不要剩力气去用)

 

4.应尽量避免在 where 子句中使用 != 或 <> 操作符,否则将引擎放弃使用索引而进行全表扫描。

 1 select id from name where id>5 

 

5.应尽量避免在 where 子句中使用 or 来连接条件,如果一个字段有索引,一个字段没有索引,将导致引擎放弃使用索引而进行全表扫描,如:

 1 select id from t where num=10 or Name = 'admin'

可以这样查询:

 1 select id from t where num = 10 2 union all 3 select id from t where Name = 'admin 

 

6:in或者not in 也慎用 如:

 1 select id from student where id in(select id from aa) 

很多时候用 exists 代替 in 是一个好的选择:

如 : 1 select id from student where id exists(select id from aa) 

 

7:like模糊查询也会导致全盘扫描 如:

 1 select id from student where name like '%kk%' 

 

8:应避免对where语句的表达式操作 如:

 1 select id from student where id=8/2 

 

9:Update 语句,如果只更改1、2个字段,不要Update全部字段,否则频繁调用会引起明显的性能消耗,同时带来大量日志。

 

10:对于多张大数据量的表JOIN,要先分页再JOIN。

 

11:select count(*) from table;这样不带任何条件的count会引起全表扫描,并且没有任何业务意义,是一定要杜绝的。

 

12:索引并不是越多越好,应正确使用索引,经常进行修改的列不适合做索引。

 

13:尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些;

 

14:尽量避免大事务操作,提高系统并发能力。

 

总结:

对于sql的优化最怕的就是避免全盘扫描,重要的事说三遍,对于sql的优化最怕的就是避免全盘扫描,对于sql的优化最怕的就是避免全盘扫描,对于sql的优化最怕的就是避免全盘扫描,杜绝***********;

posted @ 2017-12-27 19:32  曾将  阅读(174)  评论(0编辑  收藏  举报
//目录 欢迎评论,一起学习,对大家有用请点个赞。