SQL優化(一)

索引和拆分表可以極大的增加查詢速度

我們的在寫sql的時候也可以通過優化來增加查詢速度.

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

  2. 應儘量避免在where子句中對字段進行null值判斷,否則將導致引擎放棄使用索引而進行全表掃描.如:
    select * from table where colum is null
    最好不要給數據庫留null,儘可能使用NOT NULL填充數據
    備註,描述,評論之類的可以設置爲NULL,其他的最好不要使用NULL
    儘量使用varchar,因爲NULL在char類型就會佔所設置的字符數.在varchar中NULL不會佔用空間
    可以 對於數字類型的直接設置爲0

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

  4. 應儘量避免在where子句中使用 or 來連接條件,如果一個字段有索引,一個字段無索引,會導致引擎放棄使用索引,
    如: select * from table where age=10 or name=‘wlx’
    可以改成
    select * from table where age=10 union all
    select * from table where name=‘wlx’.

  5. innot in 也要慎用,否則會導致全表掃描,如
    select * from table where age in (1,2,3);
    對於連續的數值我們可以用 between 不用 in
    select * from table where age between 1 and 3
    很多時候用 exists 代替 in
    select * from table1 where age in (select age from table2); 可以用一下語句替換
    select * from table1 t1 where exists(select age from table2 where age=t1.age);

  6. 下面的查詢也 將導致全表掃描
    select * from table where name like ‘%aaaa’;
    若要提高效率,可以考慮全文檢索

  7. 如果where子句中使用參數,也會導致全表掃描.因爲SQL只有在運行時纔會解析局部變量,但優化程序不能將訪問計劃的選擇推遲到運行時;它必須在編譯時進行選擇. 然而如果在編譯時建立訪問計劃,變量的值還是未知的 ,因而無法作爲索引選擇的輸入項.如果下面語句將進行全表掃描.
    select * from table where age=@age
    可以改爲強制查詢使用索引
    select * from table with(index(索引)) where age =@age
    應儘量避免在where 子句中對字段進行表達式操作,這將導致引擎放棄使用索引而進行全表掃描.如
    select * from table age/2=11 可以改爲
    select * from table age=11*2

  8. 應儘量避免在where子句中對字段進行函數操作,這將導致引擎放棄使用索引而進行全表掃描.如
    select * from table substring(name,1,3) = ‘abc’; //查詢name以abc開頭的數據
    select * from table where datediff(createdate,‘2019-07-04’)=0 //查詢createdate和2019-07-04相等的數據
    可以改爲 select * from table where name=‘ABC%’
    select * from table where createdate>=2019-07-04 and createdate< 2019-07-04

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