學習完整課程請移步 互聯(lián)網(wǎng) Java 全棧工程師
一些常見的 SQL 實踐
- 負向條件查詢不能使用索引
select from order where status!=0 and status!=1
not in/not exists # 都不是好習慣
可以優(yōu)化為 in 查詢:
select from order where status in(2,3)
- 前導模糊查詢不能使用索引
select from order where desc like '%XX'
而非前導模糊查詢則可以:
select from order where desc like 'XX%'
- 數(shù)據(jù)區(qū)分度不大的字段不宜使用索引
select from user where sex=1
原因:性別只有男,女,每次過濾掉的數(shù)據(jù)很少,不宜使用索引。
經(jīng)驗上,能過濾80%數(shù)據(jù)時就可以使用索引。對于訂單狀態(tài),如果狀態(tài)值很少,不宜使用索引,如果狀態(tài)值很多,能夠過濾大量數(shù)據(jù),則應該建立索引。
- 在屬性上進行計算不能命中索引
select from order where YEAR(date) < = '2017'
即使date上建立了索引,也會全表掃描,可優(yōu)化為值計算:
select from order where date < = CURDATE()
或者:
select from order where date < = '2017-01-01'
并非周知的 SQL 實踐
- 如果業(yè)務大部分是單條查詢,使用Hash索引性能更好,例如用戶中心
select from user where uid=?
select from user where login_name=?
原因:B-Tree 索引的時間復雜度是 O(log(n));Hash 索引的時間復雜度是 O(1)
- 允許為
null的列,查詢有潛在大坑
單列索引不存 null 值,復合索引不存全為 null 的值,如果列允許為 null,可能會得到“不符合預期”的結果集
select from user where name != 'shenjian'
如果 name 允許為 null,索引不存儲 null 值,結果集中不會包含這些記錄。所以,請使用 not null 約束以及默認值。
- 復合索引最左前綴,并不是值 SQL 語句的
where順序要和復合索引一致
用戶中心建立了(login_name, passwd)的復合索引
select from user where login_name=? and passwd=?
select from user where passwd=? and login_name=?
都能夠命中索引
select from user where login_name=?
也能命中索引,滿足復合索引最左前綴
select from user where passwd=?
不能命中索引,不滿足復合索引最左前綴
- 使用
ENUM而不是字符串
ENUM 保存的是 TINYINT,別在枚舉中搞一些“中國”“北京”“技術部”這樣的字符串,字符串空間又大,效率又低。
小眾但有用的 SQL 實踐
- 如果明確知道只有一條結果返回,
limit 1能夠提高效率
select from user where login_name=?
可以優(yōu)化為:
select from user where login_name=? limit 1
原因:你知道只有一條結果,但數(shù)據(jù)庫并不知道,明確告訴它,讓它主動停止游標移動
- 把計算放到業(yè)務層而不是數(shù)據(jù)庫層,除了節(jié)省數(shù)據(jù)的 CPU,還有意想不到的查詢緩存優(yōu)化效果
select from order where date < = CURDATE()
這不是一個好的SQL實踐,應該優(yōu)化為:
$curDate = date('Y-m-d');
$res = mysqlquery('select from order where date < = $curDate');
原因:釋放了數(shù)據(jù)庫的 CPU,多次調用,傳入的SQL相同,才可以利用查詢緩存
- 強制類型轉換會全表掃描
select from user where phone=13800001234
你以為會命中 phone 索引么?大錯特錯了,這個語句究竟要怎么改?
末了,再加一條,不要使用 select *(潛臺詞,文章的 SQL 都不合格 ==),只返回需要的列,能夠大大的節(jié)省數(shù)據(jù)傳輸量,與數(shù)據(jù)庫的內存使用量喲。