我想弄清楚爲什麼我的一個查詢速度慢,我如何解決它,但我對我的結果有點困惑。爲什麼MySQL在查詢中使用LIMIT時速度很慢?
我有一個orders
表周圍80列和775179行和我做以下請求:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200
這在4.5S
返回38行當除去ORDER BY
我很好的改進:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL LIMIT 200
分38排在0.30s
但沒有接觸ORDER BY
我得到一個更好的結果取出LIMIT
時:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC
38排在0.10s(??)
爲什麼我的LIMIT如此飢餓?
的進一步深入
送我的答案之前注意到,我有一個指數creation_date
(這是一個datetime
)我刪除它和第一個查詢現在0.10s運行後,我嘗試了一些東西。這是爲什麼 ?
編輯
好猜,我對那裏的人列部分索引。
mysql> explain SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200;
+----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+
| 1 | SIMPLE | orders | index | id_state_idx,id_mp_idx | creation_date | 5 | NULL | 1719 | Using where |
+----+-------------+--------+-------+------------------------+---------------+---------+------+------+-------------+
1行集(0.00秒)
mysql> explain SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC;
+----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+
| 1 | SIMPLE | orders | range | id_state_idx,id_mp_idx | id_mp_idx | 3 | NULL | 87502 | Using index condition; Using where; Using filesort |
+----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+
因爲在第一次查詢後,結果被(部分)緩存爲以下查詢... – Mr47
事實並非如此,重新運行同樣的查詢給了我一致的結果 –
也許你的服務器很慢.... – pattyd