MySQL: select 5 rows before and after specific row

后端 未结 5 532
陌清茗
陌清茗 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:18

    Using union all and subqueries to limit the records should do it:

    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
    

    Sample SQL Fiddle

    Edit: I think a better method is to number the rows according to score and then select the rows with number -2 and +2 from the rows of 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;    
    

    Sample SQL Fiddle

提交回复
热议问题