优化法则归纳为5个层次:
1、 减少数据访问(减少磁盘访问)
2、 返回更少数据(减少网络传输或磁盘访问)
3、 减少交互次数(减少网络传输)
4、 减少服务器CPU开销(减少CPU及内存开销)
5、 利用更多资源(增加资源)
1、减少数据访问
1.1、创建并使用正确的索引
1.2、只通过索引访问数据
如:select id,name from company where type=’2’;
如果这个SQL经常使用,我们可以在type,id,name上创建组合索引
create index my_comb_index on company(type,id,name);
有了这个组合索引后,SQL就可以直接通过my_comb_index索引返回数据,不需要访问company表。
1.3、优化SQL执行计划
2、返回更少的数据
2.1、数据分页处理(客户端,应用服务器,数据库SQL分页)
2.2、只返回需要的字段
调整前:select * from product where company_id=?;
调整后:select id,name from product where company_id=?;
3、减少交互次数
4、减少数据库服务器CPU运算
4.1、使用绑定变量
非绑定变量写法:Select * from employee where id=1234567
绑定变量写法:Select * from employee where id=?
Preparestatement.setInt(1,1234567)
4.2、合理使用排序
4.3、减少比较操作
4.4、大量复杂运算在客户端处理
5、利用更多的资源
5.1、客户端多进程并行访问
5.2、数据库并行处理