sql优化

1.查询条件中,一定不要使用select *,因为会返回过多无用的字段会降低查询效率。应该使用具体的字段代替*,只返回使用到的字段。

2. 避免在select f1,(select f2 from tableB ).... from tableA (错)这样得到字段列。直接用tableA和tableB关联得到A.f1,B.f2就可以了。

3.避免隐含的类型转换如 :

 select id from employee where emp_id='8'  (错)
 select id from employee where emp_id=8    (对)
 emp_id是整数型,用'8'会默认启动类型转换,增加查询的开销。

4.不要在where条件中使用左右两边都是%的like模糊查询,如:

select * from t_order where customer like '%zhang%'(错)

这样会导致数据库引擎放弃索引进行全表扫描。

优化:尽量在字段后面使用模糊查询。如下:

select * from t_order where customer like 'zhang%'(对)

5.不要在字段上用转换函数,尽量在常量上用,尽量不要在where条件中等号的左侧进行表达式.函数操作,会导致全表扫描
  如:
  select id from employee where to_char(create_date,'yyyy-mm-dd')='2012-10-31'  (错)
  select * from t_order2 where substr(customer,1,5)='zhang'(错)

  select * from t_order2 where score/10 = 10(错)

将表达式.函数操作移动到等号右侧。

select id from employee where create_date=to_date('2012-10-31','yyyy-mm-dd') (对)

select * from t_order2 where customer like 'zhang%'(对)

select * from t_order2 where score = 10*10(对)

6..尽量使用exists而非in、使用not exists 而非not in
 当然这个也要根据记录的情况来定用exists还是用in, 通常的情况是用exists
 select id from employee where salary in (select salary from emp_level where....)   (错)    
 select id from employee where salary exists(select 'X' from emp_level where ....)   (对)

  对于连续的数值,能用 between 就不要用 in ,

 如下:select * from t_order where id between 2 and 3

7.尽量不要使用or,会造成全表扫描。如下:

select * from t_order where id = 1 or id = 3(错)

优化:可以用union代替or。如下:

select * from t_order where id = 1

union

select * from t_order where id = 3(对)

8.where条件里尽量不要进行null值的判断,null的判断也会造成全表扫描。如下:

select * from t_order where score is null(错)

优化:

给字段添加默认值,对默认值进行判断。如:

select * from t_order where score = 0(对)

9.不使用联接做查询

如:select id from employee where first_name || last_name like 'Jo%'  (错)

建立索引:

1.在表中建立索引,优先考虑where.group by使用到的字段。

2.一个表的索引数最好不要超过6个,如果索引太多的话,就需要考虑一下那些不常使用到的列上建的索引是否有必要。

posted @ 2019-05-19 12:48  冯小圆  阅读(167)  评论(0编辑  收藏  举报