Kcko
12/20/2018 - 9:48 PM

Prev / Next row - mysql select - variables, corelated subquery

create table example(
  id int not null primary key,
  value varchar(50)
);

insert into example
values (0,100),(2,150),(3,200),(6,250),(7,300)
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
SELECT t.id, t.value, prev_id, p.value prev_value, next_id, n.value next_value
  FROM
(
  SELECT t.id, t.value,
  (
    SELECT id
      FROM table1
     WHERE id < t.id
     ORDER BY id DESC
     LIMIT 1
  ) prev_id,
  (
    SELECT id
      FROM table1
     WHERE id > t.id
     ORDER BY id
     LIMIT 1
  ) next_id
    FROM table1 t
   WHERE t.id = 3
) t LEFT JOIN table1 p
     ON t.prev_id = p.id LEFT JOIN table1 n
     ON t.next_id = n.id