該節討論爲處理WHERE子句而進行的優化。例子中使用了SELECT語句,但相同的優化也適用DELETE和UPDATE語句中的WHERE子句。mysql
請注意對MySQL優化器的工做在不斷進行中,所以該節並不完善。MySQL執行了大量的優化,本文中所列的並不詳盡。sql
下面列出了MySQL執行的部分優化:函數
· 去除沒必要要的括號:優化
· ((a AND b) AND c OR (((a AND b) AND (c AND d))))
· -> (a AND b AND c) OR (a AND b AND c AND d)
· 常量重疊:spa
· (a<b AND b=c) AND a=5
· -> b>5 AND b=c AND a=5
· 去除常量條件(因爲常量重疊須要):排序
· (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6)
· -> B=5 OR B=6
· 索引使用的常數表達式僅計算一次。索引
下列的全部表用做常數表:隊列
mysql> SELECT * FROM t WHERE primary_key=1;
mysql> SELECT * FROM t1,t2
WHERE t1.primary_key=1 AND t2.primary_key=t1.id;
下面是一些快速查詢的例子:內存
SELECT COUNT(*) FROM tbl_name;
SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name;
SELECT MAX(key_part2) FROM tbl_name
WHERE key_part1=constant;
SELECT ... FROM tbl_name
ORDER BY key_part1,key_part2,... LIMIT 10;
SELECT ... FROM tbl_name
ORDER BY key_part1 DESC, key_part2 DESC, ... LIMIT 10;
下列查詢僅使用索引樹就能夠解決(假設索引的列爲數值型):ci
SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val;
SELECT COUNT(*) FROM tbl_name
WHERE key_part1=val1 AND key_part2=val2;
SELECT key_part2 FROM tbl_name GROUP BY key_part1;
下列查詢使用索引按排序順序檢索行,不用另外的排序:
SELECT ... FROM tbl_name
ORDER BY key_part1,key_part2,... ;
SELECT ... FROM tbl_name