且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL:选择特定行之前和之后的5行

更新时间:2023-12-03 18:28:58

使用union all和子查询来限制记录应该这样做:

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

示例SQL小提琴

我认为更好的方法是根据得分对行编号,然后从ID 5的行中选择编号为-2和+2的行:

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;    

示例SQL小提琴