天天看點

系統開發時需要注意的SQL寫法

1. 不論一個sql中涉及到多個表,每次都用兩個表(結果集)操作,得到新的結果後,再和下一個表(結果集)操作。

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. 盡量減少使用正規表達式,盡量不使用通配符。

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%'         (對)

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')   (對)

7.不使用聯接做查詢

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

8. 盡量避免前後都用通配符

  如:

  select id from employee where dept like '%TECH%' (錯)

  select id from employee where dept like 'TECH%' (對)

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   (對)

10. 盡量使用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 ....)   (對)

11. 使用not exists 而非not in

    和上面的類似

12. 減少查詢表的記錄數範圍

13.正确使用索引

  索引可以提高速度,一般來說,選擇度越高,索引的效率越高。

14. 索引類型

  唯一索引,對于查詢用到的字段,盡可能使用唯一索引。

  還有一些其他類型,如位圖索引,在性别字段,隻有男女的字段上用。

15. 在經常進行連接配接,但是沒有指定為外鍵的列上建立索引

16. 在頻繁進行排序會分組的列上建立索引,如經常做group by 或 order by 操作的字段。

17. 在條件表達式中經常用到的不同值較多的列上建立檢索,在不同值少的列上不建立索引。如性别列上隻有男,女兩個不同的值,就沒必要建立索引(或建立位圖索引)。如果建立索引不但不會提高查詢效率,反而會嚴重降低更新速度。

18. 在值比較少的字段做order by時,翻頁會出現記錄紊亂問題,要帶上id字段一起做order by.

19. 不要使用空字元串進行查詢

    如:

    select id from employee where emp_name like '%%' (錯)

20. 盡量對經常用作group by的關鍵字段做索引。

21. 正确使用表關聯

    利用外連接配接替換效率十分低下的not in運算,大大提高運作速度。

    如:

    select a.id from employee a where a.emp_no not in (select emp_no from employee1 where job ='SALE')  (錯)

22. 使用臨時表    

   在必要的情況下,為減少讀取次數,可以使用經過索引的臨時表加快速度。

   如:

   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      (對)