常用SQL语句优化技巧有哪些

50次阅读
没有评论

共计 2434 个字符,预计需要花费 7 分钟才能阅读完成。

这篇文章将为大家详细讲解有关常用 SQL 语句优化技巧有哪些,丸趣 TV 小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

具体如下:

除了建立索引之外,保持良好的 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:

例如:表 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 cc=A.cc)

效率高,用到了 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 cc=B.cc)

效率低,用到了 A 表上 cc 列的索引。

⑨避免在索引列上做如下操作:

◆避免在索引字段上使用,!=
◆避免在索引列上使用 IS NULL 和 IS NOT NULL
◆避免在索引列上出现数据类型转换(比如某字段是 String 类型,参数传入时是 int 类型)

当在索引列上使用如上操作时,索引将会失效,造成全表扫描。

⑩复杂操作可以考虑适当拆成几步

有时候会有通过一个 SQL 语句来实现复杂业务的例子出现,为了实现复杂的业务,嵌套多级子查询。造成 SQL 性能问题。对于这种情况可以考虑拆分 SQL,通过多个 SQL 语句实现,或者把部分程序能完成的工作交给程序完成。

关于“常用 SQL 语句优化技巧有哪些”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-04发表,共计2434字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)