默認(rèn)情況下,mysql對group by col1,col2 字段進(jìn)行排序,這與order by col1 col2類似,如果顯式的堆一個包含相同列的order by 子句钻蹬,實(shí)際上沒有什么影響,如果查詢group by 但是用戶想要避免不必要的排序凭需,則可以指定order by null.
優(yōu)化分頁查詢
一般查詢是,通過創(chuàng)建覆蓋索引能夠比較好的提高性能肝匆,一個常見的問題就是limit 1000,20 查詢出1020行粒蜈,但是返回的是1000到1020條數(shù)據(jù),其他數(shù)據(jù)都進(jìn)行拋棄了
1.使用主鍵回表查詢原表的記錄,下面我們發(fā)現(xiàn)直接查詢是進(jìn)行全表查詢旗国,而使用主鍵關(guān)聯(lián)回表查詢可以提高查詢效率
mysql> explain select film_id, description from film order by title limit 50,5 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: film
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 1000
Extra: Using filesort
1 row in set (0.00 sec)
mysql> explain select a.film_id,a.description from film a inner join (select film_id from film order by title limit 50,5) b on a.film_id=b.film_id \G
*************************** 1. row ***************************
id: 1
select_type: PRIMARY
table: <derived2>
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 55
Extra: NULL
*************************** 2. row ***************************
id: 1
select_type: PRIMARY
table: a
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 2
ref: b.film_id
rows: 1
Extra: NULL
*************************** 3. row ***************************
id: 2
select_type: DERIVED
table: film
type: index
possible_keys: NULL
key: idx_title
key_len: 767
ref: NULL
rows: 1000
Extra: Using index
3 rows in set (0.00 sec)
2.記錄上一次的某個位置枯怖,用記錄上一頁的最后一行的字段,在使用limit n ,
mysql> explain select * from payment where rental_id<15640 order by rental_id desc limit 10\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: payment
type: range
possible_keys: fk_payment_rental
key: fk_payment_rental
key_len: 5
ref: NULL
rows: 8043
Extra: Using index condition
1 row in set (0.00 sec)
使用排序rental_id 記錄上一頁的最后位置能曾,在根據(jù)這個位置過濾且使用limit n度硝,可以有效提高查詢的效率肿轨,但是在rental_id有大量重復(fù)的情況下,這種優(yōu)化會丟失數(shù)據(jù)蕊程。