Mysql學習總結(65)——專案實戰中常用SQL實踐總結
(1)負向條件查詢不能使用索引
- select x1, x2 from order where status!=0 and stauts!=1
not in/not exists都不是好習慣
可以優化為in查詢:
- select x1, x2 from order where status in(2,3)
(2)前導模糊查詢不能使用索引
- select x1, x2 from order where desc like '%XX'
而非前導模糊查詢則可以:
- select x1, x2 from order where desc like 'XX%'
(3)資料區分度不大的欄位不宜使用索引
- select x1, x2 from user where sex=1
原因:性別只有男,女,每次過濾掉的資料很少,不宜使用索引。經驗上,能過濾80%資料時就可以使用索引。對於訂單狀態,如果狀態值很少,不宜使用索引,如果狀態值很多,能夠過濾大量資料,則應該建立索引。
(4)在屬性上進行計算不能命中索引
- select x1, x2 from order where YEAR(date) < = '2017'
即使date上建立了索引,也會全表掃描,可優化為值計算:
- select x1, x2 from order where date < = CURDATE()
或者:
- select x1, x2 from order where date < = '2017-01-01'
(5)如果業務大部分是單條查詢,使用Hash索引效能更好,例如使用者中心
- select x1, x2 from user where uid=?
- select x1, x2 from user where login_name=?
原因:B-Tree索引的時間複雜度是O(log(n));Hash索引的時間複雜度是O(1)
(6)允許為null的列,查詢有潛在大坑
單列索引不存null值,複合索引不存全為null的值,如果列允許為null,可能會得到“不符合預期”的結果集
- select x1, x2 from user where name != 'shenjian'
如果name允許為null,索引不儲存null值,結果集中不會包含這些記錄。
所以,請使用not null約束以及預設值。
(7)複合索引最左字首,並不是值SQL語句的where順序要和複合索引一致
使用者中心建立了(login_name, passwd)的複合索引
- select x1, x2 from user where login_name=? and passwd=?
- select x1, x2 from user where passwd=? and login_name=?
都能夠命中索引
- select x1, x2 from user where login_name=?
也能命中索引,滿足複合索引最左字首
- select x1, x2 from user where passwd=?
不能命中索引,不滿足複合索引最左字首
(8)使用ENUM而不是字串
ENUM儲存的是TINYINT,別在列舉中搞一些“中國”“北京”“技術部”這樣的字串,字串空間又大,效率又低。
(9)如果明確知道只有一條結果返回,limit 1能夠提高效率
- select x1, x2 from user where login_name=?
可以優化為:
- select x1, x2 from user where login_name=? limit 1
原因:你知道只有一條結果,但資料庫並不知道,明確告訴它,讓它主動停止遊標移動
(10)把計算放到業務層而不是資料庫層,除了節省資料的CPU,還有意想不到的查詢快取優化效果
- select x1, x2 from order where date < = CURDATE()
這不是一個好的SQL實踐,應該優化為:
$curDate = date('Y-m-d');
$res = mysql_query(
'select x1, x2 from order where date < = $curDate');
原因:釋放了資料庫的CPU,多次呼叫,傳入的SQL相同,才可以利用查詢快取
(11)強制型別轉換會全表掃描
- select x1, x2 from user where phone=13800001234
你以為會命中phone索引麼?大錯特錯了