SELECT * FROM table ORDER BY id DESC LIMIT 0,25
when I checked the EXPLAIN it says that it queried 1,000,000
note: total rows of table is 1,000,000
Is there a way to optimize this query? I only wanted to get the most recent entry (let say 25 recent rows)
I don't see that there's much here that needs optimizing.
The worst case scenario is this (I have a very slightly larger table than yours):
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)
You can wait 0.2 secs, right?
If you have an index on id
, there is not a problem, other than EXPLAIN
being misleading:
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
+----------------------------+-------+
If you don't have an index (or PRIMARY KEY
) on id
, you need one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.