數據庫學習(四)---SQL優化

  1. 應避免在where子句中使用!=或<>操作符,否則將放棄使用索引而進行全表掃描。
  2. 對查詢進行優化,要儘量避免全表掃描,首先應考慮在where及order by涉及的列上建立索引。
  3. 應儘量避免在where子句中對字段進行null值判斷,否則將導致放棄使用索引而進行全表掃描,如:select id from t where num is null,最好不要給數據庫留null,儘可能的使用not null填充數據庫。
  4. 應儘量避免在where子句中使用or來連接條件,如果一個字段有索引,一個字段沒有索引,將導致放棄使用索引而進行全表掃描,如:select id from t where num = 10 or name = ‘admin’ 可以這樣查詢:select id from t where num = 10 union all select id from t where name = ‘admin’。
  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。
    很多時候用exists代替in是一個好的選擇,如:select num from t where num in(select num from b),用下面的語句替換,select num from t where exists (select 1 from b where num =t.num)。
    in 和 exists的區別: 如果子查詢得出的結果集記錄較少,主查詢中的表較大且又有索引時應該用in, 反之如果外層的主查詢記錄較少,子查詢中的表大,又有索引時使用exists。其實我們區分in和exists主要是造成了驅動順序的改變(這是性能變化的關鍵),如果是exists,那麼以外層表爲驅動表,先被訪問,如果是IN,那麼先執行子查詢,所以我們會以驅動表的快速返回爲目標,那麼就會考慮到索引及結果集的關係了 ,另外IN時不對NULL進行處理。

參考博客:https://blog.csdn.net/wqc19920906/article/details/79800374

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章