如何提高sql查詢速度


1.對查詢進行優化,應盡量避免全表掃描,首先應考慮在 where 及 order by 涉及的列上建立索引。

  2.應盡量避免在 where 子句中對字段進行 null 值判斷,否則將導致引擎放棄使用索引而進行全表掃描,如:

  select id from t where num is null

  可以在num上設置默認值0,確保表中num列沒有null值,然后這樣查詢:

  select id from t where num=0

  3.應盡量避免在 where 子句中使用!=或<>操作符,否則將引擎放棄使用索引而進行全表掃描。

  4.應盡量避免在 where 子句中使用 or 來連接條件,否則將導致引擎放棄使用索引而進行全表掃描,如:

  select id from t where num=10 or num=20

  可以這樣查詢:

  select id from t where num=10

  union all

  select id from t where num=20

  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 '%abc%'

  若要提高效率,可以考慮 全文檢索


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM