mysql select 下一条和上一条记录按字母顺序排列

mysql select next and previous record order by alpha character

我有一个包含多个公司资料的数据库 table,我想显示每个公司的资料以及之前和下一个公司 link。如果当前公司名称 'D' 那么前一个公司将是 'C' 而下一个公司将是 'E'。请帮助我。

current ->  select * from `sample` where id = 4; value is D

previous - > select * from `sample` where (need to fetch record with value c ) limit 1

next - > select * from `sample` where (need to fetch record with value e ) limit 1

您可以使用 window 函数 LAG()LEAD()

如果你想要 1 行的结果:

WITH cte AS (
  SELECT *, 
         LAG(id) OVER (ORDER BY value) prev_id,
         LEAD(id) OVER (ORDER BY value) next_id
  FROM tablename         
)
SELECT * 
FROM cte
WHERE value = 'd'

结果:

> id | value | prev_id | next_id
> -: | :---- | ------: | ------:
>  4 | d     |      11 |      12

或者如果你想要 2 行:

WITH cte AS (
  SELECT *, 
         LAG(value) OVER (ORDER BY value) prev_value,
         LEAD(value) OVER (ORDER BY value) next_value
  FROM tablename         
)
SELECT id, value
FROM cte
WHERE 'd' IN (prev_value, next_value)

结果:

> id | value
> -: | :----
> 11 | c    
> 12 | e 

参见demo