Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select max id minus one ( second last row id )

Tags:

mysql

Just wondering if there is a simple query that I could use to get the second last record when selecting max id.

SELECT MAX(`EventID`) FROM `event`;

Thank you

like image 418
Deano Avatar asked Jul 08 '13 19:07

Deano


1 Answers

You can use: EDIT: (added Bill's suggestion which is better)

SELECT (`EventID`) FROM 'event' ORDER BY 'EventID' DESC LIMIT 1 OFFSET 1

OR:

SELECT `EventID` FROM (SELECT (`EventID`) FROM 'event' ORDER BY 'EventID' DESC LIMIT 2) ORDER BY 'EventID' ASC LIMIT 1

This solution is more general and will also work if your EventID column has gaps

like image 85
Ronen Yacobi Avatar answered Sep 18 '22 10:09

Ronen Yacobi