常⽤SQL语句优化技巧总结【经典】
本⽂实例总结了常⽤SQL语句优化技巧。分享给⼤家供⼤家参考,具体如下:
除了建⽴索引之外,保持良好的SQL语句编写习惯将会降低SQL性能问题发⽣。
①通过变量的⽅式来设置参数
好:
stringsql = "select * from people p where p.id = ? ";
坏:
stringsql = "select * from people p where p.id = "+id;
数据库的SQL⽂解析和执⾏计划会保存在缓存中,但是SQL⽂只要有变化,就得重新解析。
“…where p.id = ”+id的⽅式在id值发⽣改变时需要重新解析,这会耗费时间。
②不要使⽤select *
好:
stringsql = "select people_name,pepole_age from people ";
坏:
stringsql = "select * from people ";
使⽤select *的话会增加解析的时间,另外会把不需要的数据也给查询出来,数据传输也是耗费时间的,
⽐如text类型的字段通常⽤来保存⼀些内容⽐较繁杂的东西,如果使⽤select *则会把该字段也查询出来。
③谨慎使⽤模糊查询
好:
stringsql = "select * from people p where p.id like 'parm1%' ";
坏:
stringsql = "select * from people p where p.id like '%parm1%' ";
当模糊匹配以%开头时,该列索引将失效,若不以%开头,该列索引有效。
④不要使⽤列号
好:
stringsql = "select people_name,pepole_age from people order by name,age";
坏:
stringsql = "select people_name,pepole_age from people order by 6,8";
使⽤列号的话,将会增加不必要的解析时间。
⑤优先使⽤UNION ALL,避免使⽤UNION
好:
stringsql = "select name from student union all select name from teacher";
坏:
stringsql = "select name from student union select name from teacher";
UNION 因为会将各查询⼦集的记录做⽐较,故⽐起UNION ALL ,通常速度都会慢上许多。⼀般来说,如果使⽤UNION ALL 能满⾜要求的话,务必使⽤UNION ALL。还有⼀种情况,如果业务上能够确保不会出现重复记录。
⑥在where语句或者order by语句中避免对索引字段进⾏计算操作
好:
stringsql = "select people_name,pepole_age from people where create_date=date1 ";
坏:
stringsql = "select people_name,pepole_age from people where trunc(create_date)=date1";
当在索引列上进⾏操作之后,索引将会失效。正确做法应该是将值计算好再传⼊进来。
⑦使⽤not exist代替not in
好:
stringsql = "select * from orders where customer_name not exist (select customer_name from customer)";
坏:
stringsql = "select * from orders where customer_name not in(select customer_name from customer)";
如果查询语句使⽤了not in 那么内外表都进⾏全表扫描,没有⽤到索引;⽽not extsts 的⼦查询依然能⽤到表上的索引。
⑧ exist和in的区别
in 是把外表和内表作hash 连接,⽽exists是对外表作loop循环,每次loop循环再对内表进⾏查询。因此,in⽤到的是外表的索引, exists⽤到的是内表的索引。
如果查询的两个表⼤⼩相当,那么⽤in和exists差别不⼤。
如果两个表中⼀个较⼩,⼀个是⼤表,则⼦查询表⼤的⽤exists,⼦查询表⼩的⽤in:
sql语句优化方式例如:表A(⼩表),表B(⼤表)
1:
select * from A where cc in (select cc from B)
效率低,⽤到了A表上cc列的索引;
select * from A where exists(select cc from B where )
效率⾼,⽤到了B表上cc列的索引。
2:
select * from B where cc in (select cc from A)
效率⾼,⽤到了B表上cc列的索引;
select * from B where exists(select cc from A where )
效率低,⽤到了A表上cc列的索引。
⑨避免在索引列上做如下操作:
◆避免在索引字段上使⽤<>,!=
◆避免在索引列上使⽤IS NULL和IS NOT NULL
◆避免在索引列上出现数据类型转换(⽐如某字段是String类型,参数传⼊时是int类型)
当在索引列上使⽤如上操作时,索引将会失效,造成全表扫描。
⑩复杂操作可以考虑适当拆成⼏步
有时候会有通过⼀个SQL语句来实现复杂业务的例⼦出现,为了实现复杂的业务,嵌套多级⼦查询。造成SQL性能问题。对于这种情况可以考虑拆分SQL,通过多个SQL语句实现,或者把部分程序能完成的⼯作交给程序完成。
PS:这⾥再为⼤家推荐2款SQL在线⼯具供⼤家参考使⽤:希望本⽂所述对⼤家数据库程序设计有所帮助。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论