mysql 查詢優化技巧

查詢使用索引相關

1, 避免在 sql 的 where 條件中使用 函數,會致使索引失效mysql

2, join 兩個表時,若是關聯字段數據類型不一致,請使用類型轉換函數。sql

3, sql 中的條件值必須與字段類型一致, 避免數據庫作隱式類型轉換,致使索引失效 (數據類型禁止加引號,字符串必須加引號).數據庫

4, 避免使用 左模糊 ( like '%xxx' ), 全模糊查詢。 儘可能 使用 右模糊查詢,能夠走索引。函數

5, join , in , not in , exists , not exists 性能比較性能

A, 字段上有索引: exists(好) -- in 差-- join 最差code

B, 字段上無索引 : join 好 -- exists 差 -- in 最差orm

C, 字段上有索引 : left join 好--- not exists 差 -- not in 最差排序

D, 字段上無索引 : not in 好 --- not exists 差 -- left join 最差索引

6, 儘可能不要使用 反向查詢, 例如 not in , != , not like 它們不走索引資源

7, 儘可能不要or , 不走索引 , 若是能夠用 in 代替, in 元素個數要嚴格控制, 防止 超額,建議 最大不超過 200

8, 日期字段查詢統一使用 這種格式的字符串 "yyyy-MM-dd HH:mm:ss" ; mysql 的日期類型與字符類型相同的,不須要作額外的類型轉換。 好比 select id where time >='2010-01-10 01:10:20'

9, 避免多於排序:使用 group by 時,數據庫默認是會進行排序操做的,若是 不須要,可使用 group by NULL 避免數據庫排序(提高查詢效率和 減小資源開銷) select id form user group by name order by NULL ;

  1. 業務程序禁止使用 存儲過程, 觸發器,函數,做業和視圖等, 一些特殊日期, 聚合等函數除外。

11, 儘可能使用 join 鏈接查詢 代替子查詢

12, 全部內鏈接, 需將 關聯表統一寫到 from 子句中,關聯條件和過濾條件統一寫到 where 子句中

13, 外鏈接都用 left join ,不用 right join

  1. 多表鏈接的分頁語句,若是 過濾條件在單個表上, 須要先分頁再 join 鏈接 好比 : select a.name ,b.id from ( select id,name from user where id>100 order by id limit 0,10 ) a inner join shop b where a.id = b.id;

  2. 在 iBatis 中,儘可能不要使用 $name$ , 應該採用 #name# 防止sql注入

  3. inser into 語句也必須指定具體字段名稱。 禁止寫成 insert into user values(...)

  4. SQL 中 儘可能避免出現 now() , rand() , sysdate() , current_user() 等不肯定結果的函數

  5. 禁止用 select for update 語法

其餘知識

1, insert ignore into 當 插入 數據時,如出現錯誤,重複數據, 將不返回錯誤,只以通過形式返回。因此使用 ignore 請確保語句自己沒有問題,不然也會被忽略掉 好比:

insert ignore into books(name) valuse ('xxx');

2, on duplicate key update 當 primary 或者 unique 重複時, 則執行 update 語句,在原有記錄基礎上,更新指定字段內容, 其餘字段內容保留,若是 update 後爲無用語句,如id =id ,錯誤不會被忽略,爲了實現 name 重複的數據插入不報錯,可以使用 下語句:

insert into books(name) values 'xxx' 
on duplicate key update id=id ;

3, insert ... select ... where not exist 根據 select 的條件判斷是否插入, 能夠不光經過 primary 和 unique來判斷, 也能夠經過其餘條件

insert into books(name) 
select id  from dual where 
not exists (select id from books where id=1)

4, replace into 若是存在 primary or unique 相同的記錄, 則先刪除再插入新的記錄。 若是記錄有多個字段,在插入的時候若是有的字段 沒有賦值,那麼新插入的記錄字段爲空

replace into books select 1 from books

以上 來自 書籍 BAT 公司員工的MYSQL 修爲

相關文章
相關標籤/搜索