选择第二个最高时间戳和相关列

时间:2018-02-01 12:12:02

标签: mysql correlated-subquery

在带有行李的桌子中,每个行李都有一个位置列和时间列,我可以通过此查询获取最新的位置:

SELECT b.* 
FROM bag_position b 
WHERE time = ( 
    SELECT MAX(c.time) 
    FROM bag_position c 
    WHERE c.bag_id = b.bag_id 
);

我怎样才能获得第二高的位置?我试过这个,但它不起作用:

SELECT b.*
from bag_position b
where time = ( select max(c.time) from bag_position c where c.time < (select max d.time from bag_position d) and c.bag_id = b.bag_id );

1 个答案:

答案 0 :(得分:1)

您可以使用offsetlimit代替max()

select b.*
from bag_position b
where b.time = (select b2.time
                from bag_position b2
                where b2.bag_id = b.bag_id
                order by time desc
                limit 1 offset 1
               );