7

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

Deano
  • 11,582
  • 18
  • 69
  • 119

5 Answers5

13

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

Ronen Yacobi
  • 844
  • 9
  • 16
  • 2
    +1 but you can do this without a subquery by using LIMIT with OFFSET. – Bill Karwin Jul 08 '13 at 19:51
  • the one with offset is a nice idea :) the second one could return the last eventID -and not the last second- if there's only one row in the table (because LIMIT 2 will return just one row in that case) – fthiella Jul 08 '13 at 20:07
6
SELECT MAX(EventID)
FROM   event
WHERE  EventID<(SELECT MAX(EventID) FROM event)
fthiella
  • 48,073
  • 15
  • 90
  • 106
0
select max(billno) from bill_information

enter image description here

solution

select max(billno) from bill_information where billno <(select max(billno) from bill_information)

enter image description here


This will help if you making billing software.That the billno (primary key with indexed) deleted and you want the billno between the billno

--213763 billno
select max(billno) from bill_information where billno <213763

enter image description here

lava
  • 6,020
  • 2
  • 31
  • 28
-2

i did something similar to this

$query_anakuklwsh = "SELECT * FROM anakuklwsh WHERE id=".$row_anakuklwsh['id']." -1";

-3

I actually managed to figure it out

  SELECT MAX(`EventID`) FROM `event` WHERE `EventID` = (SELECT MAX(`EventID`) -1 FROM `event`);
Deano
  • 11,582
  • 18
  • 69
  • 119