天天看點

SQL筆記--第四章

1 索引弊端:占用額外的磁盤空間,降低寫操作。

2 索引準則

(1)最适合索引的列是出現在WHERE子句的列,或連接配接子句中指定的列

(2)唯一值的列,索引效果最好

(3)使用短索引。對串列進行索引,應指定一個字首長度

(4)利用最左字首。N列作為一個索引,則可利用N個索引。如:state city zip作為一個索引。則可用索引state,state city,state city zip

(5)不要過度索引

(6)考慮在列上進行的比較類型。索引可用于< <= + >= > between。若列用于其他類型的運算,對其進行索引沒有價值。

3 explain顯示如何使用索引處理select以及連接配接表。用于選擇更好的索引和寫出更優化的查詢語句。

4 索引優化

(1)比較中盡量傅索引列獨立,如

應為 where my_col < 4/2

不應為 where my_col * 2 <4

應為 where date_col < "1900-01-01"

不應為 where year(date_col) < 1900

應為 where date_col < date_add(current_date, interval cutoff day)

不應為 where to_days(date_col) - to_days(current_date) < cutoff

(2)LIKE模式轉換

應為 where last_name >= "Mac" and last_name < "Mad"

不應為 where last_name like "Mac%"

5 索引列類型選擇

(1)使用定長列

(2)盡量使用較短的列

(3)将列定義為NOT NULL

(4)考慮使用ENUM列

(5)使用procedure analyse(),擷取列的選擇

select * from tbl_name procedure analyse()

(6)避免檢索較大的BLOB或TEXT值

(7)将BLOB值隔離在一個獨立的表中

6 成批裝載較單行快,因為不需要重新整理索引,裝完後才重新整理

無索引比索引裝載快

7 寫入請求按其到達的次序進行處理

寫入具有比讀取更高的優先權

可通過關鍵字改變優先級

insert low_priority into tbl_name values();

high_priority

8 寫入延遲,對innodb無效

對myisam有效,insert delayed into tbl_name values()