SQL语句奇淫巧技

  1. 不论一个sql中涉及到多个表,每次都用两个表(结果集)操作,得到新的结果后,再和下一个表(结果集)操作。
  2. 避免在select f1,(select f2 from tableB )… from tableA 这样得到字段列。直接用tableA和tableB关联得到A.f1,B.f2就可以了。
  3. 避免隐含的类型转换
 # 假如 emp_id是整数型,用'8'会默认启动类型转换,增加查询的开销。
 select id from employee where emp_id='8'  (错)
 select id from employee where emp_id=8    (对)

4.尽量减少使用正则表达式,尽量不使用通配符。
5.使用关键字代替函数

   #如:
   select id from employee where UPPER(dept) like 'TECH_DB'  (错)
   select id from employee where SUBSTR(dept,1,4)='TECH'    (错)
   select id from employee where dept like 'TECH%'         (对)
  1. 尽量使用exists而非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 ....)   (对)
  1. 使用not exists 而非not in
    和上面的类似

6.不要在字段上用转换函数,尽量在常量上用
如:
select id from employee where to_char(create_date,‘yyyy-mm-dd’)=‘2012-10-31’ (错)
select id from employee where create_date=to_date(‘2012-10-31’,‘yyyy-mm-dd’) (对)
9. 判断条件顺序
如:
select id from employee where creat_date-30>to_date(‘2012-10-31’,‘yyyy-mm-dd’) (错)
select id from employee where creat_date >to_date(‘2012-10-31’,‘yyyy-mm-dd’)+30 (对)

  1. 正确使用表关联
    利用外连接替换效率十分低下的not in运算,大大提高运行速度。
如:
select a.id from employee a where a.emp_no not in (select emp_no from employee1 where job ='SALE')  (错)

7.不使用联接做查询
如:select id from employee where first_name || last_name like ‘Jo%’ (错)

  1. 使用临时表
    在必要的情况下,为减少读取次数,可以使用经过索引的临时表加快速度。
    如:
    select e.id from employee e ,dept d where e.dept_id=d.id and e.empno>1000 order by e.id (错)

select id,empno from employee into temp_empl where empno>1000 order by id
select m.id from temp_emp1 m,dept d where m.empno=d.id (对)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值