標籤:mysql mysql最佳化 mysql排序最佳化
今天資料庫負載就直線上升,資料庫連接數撐爆。把語句抓出來一看,罪魁禍首是一條很簡單的語句:SELECT * FROM eload_promotion_code WHERE 1 AND exp_time<1478782591 AND cishu=0 order by id desc limit 454660,20; 二話不說先把這個語句kill了,然後慢慢看怎麼最佳化。
先看一下這個表的索引:
>show index from eload_promotion_code\G
*************************** 1. row ***************************
Table: eload_promotion_code
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 921642
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
*************************** 2. row ***************************
Table: eload_promotion_code
Non_unique: 1
Key_name: idx_cishu_exp
Seq_in_index: 1
Column_name: cishu
Collation: A
Cardinality: 15
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
*************************** 3. row ***************************
Table: eload_promotion_code
Non_unique: 1
Key_name: idx_cishu_exp
Seq_in_index: 2
Column_name: exp_time
Collation: A
Cardinality: 921642
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
可以看到id為主鍵,idx_cishu_exp為(cishu,exp_time)的唯一索引
看一下這個語句的執行計畫,可以看到排序沒有用到索引
.*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: eload_promotion_code
type: ref
possible_keys: idx_cishu_exp
key: idx_cishu_exp
key_len: 4
ref: const
rows: 460854
Extra: Using where; Using filesort
1 row in set (0.00 sec)
將select * 換成select id後再看執行計畫,可以用索引覆蓋
>explain select id FROM eload_promotion_code WHERE 1 AND exp_time<1478782591 AND cishu=0 order by id desc limit 454660,20 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: eload_promotion_code
type: range
possible_keys: idx_cishu_exp
key: idx_cishu_exp
key_len: 8
ref: NULL
rows: 460862
Extra: Using where; Using index; Using filesort
1 row in set (0.00 sec)
好吧,這個語句有救了,採用延時關聯先取出id,然後根據id擷取原表所需要的行,改寫後的語句來了:select * from eload_promotion_code inner join (select id from eload_promotion_code where exp_time<1478782591 AND cishu=0 order by id desc limit 454660,20) as x on eload_promotion_code.id=x.id;
執行一下,0.3s出結果。
這樣就算完了。
本文出自 “一直在路上” 部落格,請務必保留此出處http://chenql.blog.51cto.com/8732050/1871609
mysql倒排的最佳化