Mysql
 sql >> Database >  >> RDS >> Mysql

MySQL:seleziona 5 righe prima e dopo una riga specifica

Usando union all e le sottoquery per limitare i record dovrebbero farlo:

select * from  users where id = 5
union all (
  select * from users 
  where score <  (select score from users where id = 5) 
  order by score desc limit 2
) 
union all (
  select * from users 
  where score > (select score from users where id = 5) 
  order by score asc limit 2
) 
order by score

Campione SQL Fiddle

Modifica:penso che un metodo migliore sia numerare le righe in base al punteggio e quindi selezionare le righe con il numero -2 e +2 dalle righe dell'id 5:

select id, name, score 
from (select 
      t.*, @rownum1 := @rownum1 + 1 as rank
      from users t, (select @rownum1 := 0) r
      order by score
     ) a,
     (select rank from (
        select t.*, 
        @rownum := @rownum + 1 as rank
        from users t, (select @rownum := 0) r
        order by score
     ) t
      where id = 5
   ) b
where b.rank between a.rank -2 and a.rank+2
order by score;    

Campione SQL Fiddle