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

时间:2015-03-24 08:50:35

标签: mysql

我有一个名为"用户"并且需要在特定行之前和之后选择2行,按users.score ASC

排序

用户表(结构):

id     name     score
1      John       2
2      Sara       1
3      san        3
4      test       2
5      jery       5
6      simon      6
7      bob2       7
8      jack       4
9      man        2

例如:需要在users.id = 5之前和之后选择2行by users.score

结果应该是:

id     name     score
3      san        3
8      jack       4
5      jery       5
6      simon      6
7      bob2       7

感谢,

5 个答案:

答案 0 :(得分:6)

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

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

<击>

<击>

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

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

<击>

答案 1 :(得分:2)

也许使用union all

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

答案 2 :(得分:1)

(SELECT x.* FROM users x JOIN users y ON y.score <= x. score WHERE y.id = 5 ORDER BY score LIMIT 3)
UNION
(SELECT x.* FROM users x JOIN users y ON y.score >= x. score WHERE y.id = 5 ORDER BY score DESc LIMIT 3)
[ORDER BY score]    ;

http://www.sqlfiddle.com/#!9/45c22/42

答案 3 :(得分:0)

我只是编写查询,基于&#34; jpw&#34;解决方案(非常感谢他)

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

答案 4 :(得分:0)

在特定ID

之前和之后选择任意排序的行
SET @j = 0;
SET @i = 0;
SELECT *
FROM ( 
    SELECT id, col1, col2, ..., @j:=@j+1 AS pos
    FROM `table`
    WHERE  col1=... ORDER BY col1 DESC, col2 ASC
) AS zz
WHERE (    
    SELECT position
    FROM ( 
        SELECT id AS id2, @i:=@i+1 AS position
        FROM `table`
        WHERE  col1=... ORDER BY col1 DESC, col2 ASC
    ) AS zz
    WHERE id2=$currId
)
IN (pos-5,pos-4,pos-3,pos-2,pos-1,pos,pos+1,pos+2,pos+3,pos+4,pos+5)