GroupBy和索引的關(guān)系

默認(rèn)情況下,mysql對group by col1,col2 字段進(jìn)行排序,這與order by col1 col2類似,如果顯式的堆一個(gè)包含相同列的order by 子句,實(shí)際上沒有什么影響,如果查詢group by 但是用戶想要避免不必要的排序,則可以指定order by null.

優(yōu)化分頁查詢

一般查詢是,通過創(chuàng)建覆蓋索引能夠比較好的提高性能,一個(gè)常見的問題就是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.記錄上一次的某個(gè)位置,用記錄上一頁的最后一行的字段,在使用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ù)這個(gè)位置過濾且使用limit n,可以有效提高查詢的效率,但是在rental_id有大量重復(fù)的情況下,這種優(yōu)化會(huì)丟失數(shù)據(jù)。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容