获取当前行以及下一个和上一个记录

时间:2014-04-24 15:32:36

标签: mysql

我有一个获取当前记录的查询,以及下一个和上一个记录。但我需要这样做,以便它不必成为下一个连续的ID。

select u.user_id, u.first_name, u.last_name, u.username,
    (select user_id -1 as user_id from users where user_id = u.user_id) as prev_id,
    (select user_id +1 as user_id from users where user_id = u.user_id) as next_id
from users u
where u.user_id = 3

这会返回我需要的内容,但如果user_id 4不存在,我将如何获得下一条记录?

此外,这是最快的方法吗?

感谢您的帮助?

3 个答案:

答案 0 :(得分:1)

您可以使用限制来获取下一个和上一个ID。例如:

  select
          u.user_id,
          u.first_name,
          u.last_name,
          u.username,
          (select user_id as user_id 
           from users 
           where user_id <u.user_id 
           order by user_id desc
           limit 1 ) as prev_id,
           (select user_id as user_id 
           from users 
           where user_id >u.user_id 
           order by user_id asc
           limit 1 ) as next_id
        from users u
        where u.user_id = 3

答案 1 :(得分:1)

使用几个连接和聚合函数: -

select u.user_id, u.first_name, u.last_name, u.username,
    MAX(u_prev.user_id) AS prev_id,
    MIN(u_next.user_id) AS next_id
from users u
LEFT OUTER JOIN user u_prev ON u.user_id > u_prev.user_id
LEFT OUTER JOIN user u_next ON u.user_id < u_next.user_id
where u.user_id = 3
GROUP BY u.user_id, u.first_name, u.last_name, u.username

答案 2 :(得分:0)

SELECT * 
FROM `user` 
WHERE id >= (
 SELECT id 
 FROM `user` 
 WHERE id < (SELECT id FROM `user` WHERE firstname = 'abc')
 ORDER BY id DESC 
 LIMIT 1
)
ORDER BY id ASC
LIMIT 3

希望这会对你有所帮助。