简体   繁体   中英

Is there a way to select the maximum row id in MySQL without scanning all rows with MAX()?

I use the following query to get the highest id of a set of rows, but since in some cases, there are tens of thousands or hundreds of thousands of rows in the set, making the query very inefficient. Is there a way to accomplish the same result in a more efficient way?

SELECT MAX(id) FROM table WHERE groupID = '12345'

The ugly fix is to add an index on groupID, id

alter table `table` add index groupId_with_id_idx (groupId, id);
desc SELECT MAX(id) FROM table use index (groupId_with_id_idx) WHERE groupID=12345;
/* the execution plan should return "Select tables optimized away" */

What is Select tables optimized away?

If the column is an AutoNumber Identity Column, you could do something like:

 IDENT_CURRENT('table')

But that could be hit or miss. If you are using it with a where, i doubt it would get you what you want.

Cheers,

替代查询

SELECT * FROM table WHERE groupID = '12345' ORDER BY id DESC LIMIT 1;

I believe it would be faster to even ORDER BY id and pick the LIMIT 1 occurrence of groupid, but MySQL can't use an index when you're ordering by a key and fetching another constant key because it's still reading each line.

If you ORDER BY groupid (asc or desc), is the first or last record within that groupid always the highest id? Then your fastest query would be to order by groupid and select LIMIT 1 for the first record listed in that groupid.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM