If you are using MySQL, you can avoid the (rather messy) double sub-query by using LIMIT
& OFFSET
Just add order by booking_id desc LIMIT 1 OFFSET 1
and you will get the second highest booking_id
. For example ...
select * from booking where user_id = 1 order by booking_id desc OFFSET 1 LIMIT 1
I tested this on one of my tables & it worked fine. If you have an index on booking_id
it should be really fast.
If you want the second highest booking for the user who holds the highest booking, then this should work
SELECT * FROM booking
WHERE user_id in
(select user_id from booking order by booking_id desc limit 1)
ORDER BY booking_id DESC LIMIT 1 OFFSET 1
The sub-query finds the user_id
of the user with the highest booking, then the main query finds their second highest booking
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…