Mysql排名与上下游客

时间:2012-09-26 00:47:55

标签: mysql

我希望使用mysql查询从表中获得范围排名。

表格是这样的,

+------------+------+
| first_name | age  |
+------------+------+
| Kathy      |   2  |
| Jane       |   1  |
| Nick       |   3  |
| Bob        |   5  |
| Anne       |   4  |
| Jack       |   6  |
| Bill       |   8  |
| Steve      |   7  |
+------------+------+

我希望得到杰克的2名中低级上尉的排名。

+------------+------+
| Anne       |   4  |
| Bob        |   5  |
| Jack       |   6  |
| Steve      |   7  |
| Bill       |   8  |
+------------+------+

知道如何为MySQL数据库编写此查询吗?

2 个答案:

答案 0 :(得分:3)

通过将rownumber应用于记录,这是一种非常难看的方法。通过将rownumber应用于记录,那么如果年龄不连续,您将能够返回行(使用Non-consecutive ages进行演示):

select age, first_name
from 
(
  select t1.age, t1.first_name, @rownum:=@rownum+1 AS rownum
  from yourtable t1, (SELECT @rownum:=0) r
  order by t1.age
) x
where rownum  >= (select rownum
                  from 
                  (
                    select t.age, 
                      t.first_name, 
                      @rownum:=@rownum+1 AS rownum
                    from yourtable t, (SELECT @rownum:=0) r
                    order by t.age
                  ) x
                  where first_name = 'jack') - 2
 and rownum  <= (select rownum
                    from 
                    (
                      select t.age, 
                        t.first_name, 
                        @rownum:=@rownum+1 AS rownum
                      from yourtable t, (SELECT @rownum:=0) r
                      order by t.age
                    ) x
                    where first_name = 'jack') + 2;

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

工作示例:

SELECT * FROM yourtable WHERE id BETWEEN ((SELECT id FROM yourtable WHERE name = 'Jack') - 2) AND ((SELECT id FROM yourtable WHERE name = 'Jack') + 2);

SQL Fiddle Demo