Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: select 5 rows before and after specific row

Tags:

mysql

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     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

for example: need to select 2 rows before and after users.id = 5 order by users.score

result should be like:

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

thanks,

like image 613
mwafi Avatar asked Mar 24 '15 08:03

mwafi


People also ask

How do I select a specific row in MySQL?

MySQL SELECT specific rows When a user wants to retrieve some individual rows from a table, a WHERE clause has to be added with the SELECT statement immediately followed by a condition. Here * indicates all columns.

How do I select the first 10 rows in MySQL?

To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I select only certain rows in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.


1 Answers

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

like image 140
jpw Avatar answered Oct 22 '22 15:10

jpw