MySQL: select 5 rows before and after specific row

后端 未结 5 518
陌清茗
陌清茗 2020-12-20 23:26

I have table called \"users\" and need to select 2 rows before and after specific row, sorted by users.score ASC

users table (structure):

id     name         


        
5条回答
  •  天命终不由人
    2020-12-21 00:23

    I just write the query, based on "jpw" solution (many thanks to him)

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

提交回复
热议问题