获取下一个 max(id)

Get the next max(id)

我有以下 table:

booking_id user_id
11 1
12 76
13 932
14 1
15 626
16 1
17 3232

我想访问用户 1 的第二个最大值 booking_id。 预期结果是 user_id = 1, booking_id = 14.

我已经在这些地狱般的火焰上工作了太久,这没有任何好处:

select booking.user_id, b1.booking_id from booking 
left join(select 
            user_id, 
            booking_id 
          from booking 

          where booking_id = (select 
                                max(booking_id) 
                              from booking 
                              where booking_id <> (select 
                                                     max(booking_id) 
                                                   from booking)) 
        group by user_id) 
as b1 on b1.user_id = booking.user_id
where booking.user_id = '1'

请注意,我已经设法将其作为计算列来完成,但这没有用,我需要派生的 table。

通过使用本题的答案什么是最简单的SQL求第二大值的查询?

您可以像这样与您的查询集成:

select * from booking 
where booking_id =
(select max(booking_id) from booking
where user_id =1 
and booking_id not in (SELECT MAX(booking_id ) FROM booking  ))

一个简单的方法是使用 LIMIT OFFSET:

SELECT *
FROM booking
WHERE user_id = 1
ORDER BY booking_id DESC
LIMIT 1 OFFSET 1

Demo here

如果您使用 MySQL,您可以使用 LIMIT & OFFSET

来避免(相当混乱的)双重子查询

只需添加order by booking_id desc LIMIT 1 OFFSET 1,您将获得第二高的booking_id。例如...

select * from booking where user_id = 1 order by booking_id desc OFFSET 1 LIMIT 1

我在我的一张桌子上对此进行了测试,效果很好。如果你在 booking_id 上有一个索引,它应该非常快。

如果您希望预订量最高的用户获得第二高的预订量,那么这应该可行

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 

子查询找到预订最高的用户user_id,然后主查询找到他们第二高的预订