create table test (
id int primary key auto_increment,
subject_id int
);
insert into test(subject_id) values (5),(6),(6),(5),(6),(5);
select
id, subject_id,
lag(id) over w as prev_id,
lead(id) over w next_id
from test
window w AS (PARTITION BY subject_id ORDER BY id asc);