SQL SERVER中一些常见性能问题的总结

mac2022-06-30  29

1.对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。

2.应尽量避免使用 left join 和 null 值判断。left join 比 inner join 消耗更多的资源,因为它们包含与 null (不存在)数据匹配的数据,所以如果可以重新编写查询以使得该查询不使用任何 inner join ,则会得到相应的回报。例如有两表:product(product_id int not null,product_type_id int null,...),产品表, product_id 为大于0的整数, product_type_id 与表 product_type 关联,但可为空,因为有的产品没有类别product_type(product_type_id not null,product_type_name null,...),产品类别表此时要关联两表后查询 product 的内容,马上会想到使用 inner join ,但下面有一种方法可避免使用 inner join :在 product_type 中增加一条记录:0,'',...,并将 product 的 product_type_id 设置为 not null ,当产品没有类别时将其 product_type_id 设为0,这样查询就可以使用 inner join 了。

3.应尽量避免在 where 子句中使用!=或<>操作符,否则引擎可能放弃使用索引而进行全表扫描。

4.应尽量避免在 where 子句中使用 or 来连接条件,否则将可能导致引擎放弃使用索引而进行全表扫描,如有表 t , key1 、 key2 上建有索引,需要下面的存储过程:create procedure select_proc1 @key1 int=0,@key2 int=0asbegin  select key3 from t  where (@key1=0 or key1=@key1)  and (@key2=0 or key2=@key2)endgo这个存储过程会导致全表扫描,可作如下修改:create procedure select_proc2 @key1 int=0,@key2 int=0asbegin  if @key1 <>0 and @key2<>0  select key3 from t  where key1=@key1 and key2=@key2  else  if @key1<>0  select key3 from t where key1=@key1  else  select key3 from t where key2=@key2endgo更改后虽然代码增加了,但效率提高了。

5.in 和 not in 也要慎用,如:select id from t where num in(1,2,3)对于连续的数值,能用 between 就不要用 in 了:select id from t where num between 1 and 3

6.下面的查询也将导致全表扫描:select id from t where name like '

转载请注明原文地址: https://mac.8miu.com/read-63350.html
最新回复(0)