MySql - How get value in previous row and value in next row? [duplicate]

Select the next row below:

SELECT * FROM Example WHERE id < 3 ORDER BY id DESC LIMIT 1

Select the next row above:

SELECT * FROM Example WHERE id > 3 ORDER BY id LIMIT 1

Select both in one query, e.g. use UNION:

(SELECT * FROM Example WHERE id < 3 ORDER BY id DESC LIMIT 1)
 UNION
(SELECT * FROM Example WHERE id > 3 ORDER BY id LIMIT 1)

That what you mean?


A solution would be to use temporary variables:

select 
    @prev as previous,
    e.id,
    @prev := e.value as current
from
    (
        select
            @prev := null
    ) as i,
    example as e
order by
    e.id

To get the "next" value, repeat the procedure. Here is an example:

select 
  id, previous, current, next
from
  (
    select
      @next as next,
      @next := current as current,
      previous,
      id
    from
      (
        select @next := null
      ) as init,
      (
        select
          @prev as previous,
          @prev := e.value as current,
          e.id
        from
          (
            select @prev := null
          ) as init,
          example as e
        order by e.id
      ) as a
    order by
      a.id desc
  ) as b
order by
  id

Check the example on SQL Fiddle

May be overkill, but it may help you