数据库性能优化三:程序操作优化提升性能
数据库优化包含以下三部分,数据库自身的优化,数据库表优化,程序操作优化.此文为第三部分
概述:程序访问优化也可以认为是访问SQL语句的优化,一个好的SQL语句是可以减少非常多的程序性能的,下面列出常用错误习惯,并且提出相应的解决方案
一、操作符优化
二、SQL语句优化
1、在查询中不要使用select *
为什么不能使用,地球人都知道,但是很多人都习惯这样用,要明白能省就省,而且这样查询数据库不能利用“覆盖索引”了
三、where使用原则
1)在下面两条select语句中:
select * from table1 where field1<=10000 and field1>=0;
select * from table1 where field1>=0 and field1<=10000;
如果数据表中的数据field1都>=0,则第一条select语句要比第二条select语句效率高的多,因为第二条select语句的第一个条件耗费了大量的系统资源。
第一个原则:在where子句中应把最具限制性的条件放在最前面。
2)在下面的select语句中:
select * from tab where a=… and b=… and c=…;
若有索引index(a,b,c),则where子句中字段的顺序应和索引中字段顺序一致。
第二个原则:where子句中字段的顺序应和索引中字段顺序一致。
以下假设在field1上有唯一索引I1,在field2上有非唯一索引I2。
3) select field3,field4 from tb where field1='sdf' 快
select * from tb where field1='sdf' 慢,
因为后者在索引扫描后要多一步ROWID表访问。
select field3,field4 from tb where field1>='sdf' 快
select field3,field4 from tb where field1>'sdf' 慢
因为前者可以迅速定位索引。
select field3,field4 from tb where field2 like 'R%' 快
select field3,field4 from tb where field2 like '%R' 慢,
因为后者不使用索引。
4) 使用函数如:
select field3,field4 from tb where upper(field2)='RMN'不使用索引。
如果一个表有两万条记录,建议不使用函数;如果一个表有五万条以上记录,严格禁止使用函数!两万条记录以下没有限制。
如果觉得我的文章对您有用,请点赞。您的支持将鼓励我继续创作!
赞4
添加新评论0 条评论