我试图弄清楚为什么我的查询之一很慢以及如何解决它,但我对我的结果有点困惑。
我有一个orders
大约 80 列和 775179 行的表,我正在执行以下请求:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC LIMIT 200
在 4.5 秒内返回 38 行
删除时ORDER BY
我得到了很好的改进:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL LIMIT 200
0.30s 38 行
但是,在LIMIT
不接触的情况下移除时,ORDER BY
我得到了更好的结果:
SELECT * FROM orders WHERE id_state = 2 AND id_mp IS NOT NULL ORDER BY creation_date DESC
0.10 秒内 38 行 (??)
为什么我的 LIMIT 这么饿?
走得更远
我在发送答案之前尝试了一些事情,在注意到我有一个索引creation_date
(即 a datetime
)之后,我删除了它,第一个查询现在在 0.10 秒内运行。这是为什么 ?
编辑
很好的猜测,我在 where 的其他列上有索引。
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 |
+----+-------------+--------+-------+------------------------+-----------+---------+------+-------+----------------------------------------------------+