SELECT * FROM table ORDER BY id DESC LIMIT 0,25
当我检查 EXPLAIN 时,它说它查询了1,000,000
注意:表的总行数为1,000,000
有没有办法优化此查询?我只想获得最近的条目(比如25个最近的行)
答案 0 :(得分:0)
我不知道这里有很多需要优化的地方。
最糟糕的情况就是这个(我的桌子比你的桌子略大):
SELECT * FROM n ORDER BY id DESC LIMIT 1048552,25;
+----+
| id |
+----+
| 24 |
| 23 |
| 22 |
| 21 |
| 20 |
| 19 |
| 18 |
| 17 |
| 16 |
| 15 |
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
| 9 |
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 1 |
+----+
24 rows in set (0.20 sec)
你可以等0.2秒,对吧?
答案 1 :(得分:0)
如果您有id
的索引,除了EXPLAIN
误导之外没有问题:
mysql> SELECT COUNT(*) FROM canada;
+----------+
| COUNT(*) |
+----------+
| 5484 |
+----------+
mysql> FLUSH STATUS;
mysql> SELECT * FROM canada ORDER BY id DESC LIMIT 5;
+--------+---------+----------------+------------------+-------+------------+---------+----------+--------+------------------+
| id | country | ascii_city | city | state | population | lat | lng | stripe | province |
+--------+---------+----------------+------------------+-------+------------+---------+----------+--------+------------------+
| 297207 | ca | | (dup population) | | 6124 | 0 | 0 | 0 | Nunavut |
| 297206 | ca | zehner | Zehner | 11 | 0 | 50.5667 | -104.45 | 970 | Saskatchewan |
| 297205 | ca | zeballos | Zeballos | 02 | 0 | 49.9833 | -126.85 | 966 | British Columbia |
| 297204 | ca | zealandia | Zealandia | 11 | 0 | 51.6167 | -107.75 | 977 | Saskatchewan |
| 297203 | ca | yukon crossing | Yukon Crossing | 12 | 0 | 62.3333 | -136.483 | 1051 | Yukon |
+--------+---------+----------------+------------------+-------+------------+---------+----------+--------+------------------+
5 rows in set (0.01 sec)
mysql> SHOW SESSION STATUS LIKE 'Handler%';
+----------------------------+-------+
| Variable_name | Value |
+----------------------------+-------+
| Handler_commit | 1 |
| Handler_external_lock | 2 |
| Handler_read_key | 1 |
| Handler_read_last | 1 |
| Handler_read_prev | 4 | -- 1 less than LIMIT 5
+----------------------------+-------+
如果PRIMARY KEY
上没有索引(或id
),则需要索引。