【网学网提醒】:网学会员编辑为广大网友搜集整理了:Sql的一些基本技巧绩等信息,祝愿广大网友取得需要的信息,参考学习。
Sql优化一、只选择需要的字段,不要无条件选择所有字段。这样的话在一个内存页面中可以装入尽可能多的记录,减少和数据库的交互。
?Select*fromffhzwhere…?Selectzh,hm,yefromffhzwhere…二、where条件中对于索引字段尽量不要使用函数。因为这样不会使用到索引。?Select*fromffhzwherezh=‘12345’?Select*fromffhzwheresubstr(zh,1,5)=‘12345’?Select*fromffhzwherea||b=‘12345’三、尽可能条件相同,写程序的时候尽量使用参数,而不要使用写死的动态sql。尽可能使用到数据库的缓存?Select*fromffhzwherezh=??Select*fromffhzwherezh=‘123’?Select*fromffhzwherezh=‘345’四、用exists语法,而少用in的语法。In要遍历所有记录,而exists只找到一条满足条件的记录就会中止。?Select*fromfhqfhwherezhin(selectzhkhfromflsmxz)?Select*fromfhqfhwhereexists(selectzhkhfromflsmxzwherefhqfh.zh=flsmxz.zhkh)五、如果不需要取全部的记录,最好只取前多少条记录。Informix:?selectfirst100*fromaaaOracle:?select*fromaaawhererownum=100Db2:?select*fromaaafetchfrist100rowsonly六、建立索引在种类最多的字段,这样才能尽可能使用到索引。?如对ffhz的hbh建立一个索引?对zh建一个索引七、不要过多的表联合查询,最好不要超过三个。越少越好,可以适当使用临时表。尽可能用唯一条件进行关联。?Select*froma,b,c,d,ewherea.x=b.x…?Select*froma,b,cwhere…intotemptemp1?Select*fromd,ewhere…intotemptemp2?Select*fromtemp1,temp2where…八、使用betweenand语法,而不是like,这样可以尽可能使用索引。?Select*fromffhzwherezhlike‘9%’?Select*fromffhzwherezhbetween‘9000000000000000’and‘9999999999999999’九、少使用!=、<>(全表扫描,不会利用索引),可以使用>,<,>=,<=等操作。a是整型,是索引字段。
?Select*fromaaawherea!=1;?Select*fromaaawherea<=0ora>=2十、对于大批量导入数据后,可以考虑重建索引,减少索引层数。?如历史明细的索引Index1:ZhkhIndex2:Jyrq+zxlshIndex3:Jyrq+gy1+gylsh十一、更新索引统计?InformixUpdatestatistics…?Oracleanalyzetable…?db2Runstatsontable…十二、了解数据库的查询策略?Informixsetexplainon?Oracle查询分析器?Db2db2expln十三、最重要的一点?多做测试?对于使用比较频繁或估计以后会处理较多数据的地方,应构造尽可能多的数据进行测试,以便发现效率问题。拿0371gd,公司为例,其中的SQL代码查询不少于100条,经过优化后,只需要20条就可以了,减少了代码的复杂度