I'm trying to figure out how to Select a specific number of rows from a MySQL table based on WHERE clause. I have a table with 10 dummy users, I want to get 2 previous and 2 next users of specific user with their ranks.
user_id | points
==================
10 200
4 130
2 540
13 230
15 900
11 300
3 600
17 110
20 140
1 430
5 800
I achieved adding a column for ranking like:
user_id | points | rank
===========================
15 900 1
5 800 2
3 600 3
2 540 4
1 430 5
11 300 6
13 230 7
10 200 8
20 140 9
4 130 10
17 110 11
But the problem is that I want only 5 rows. Suppose I'm retrieving data for user with user_id = 11. The output should look like this:
user_id | points | rank
===========================
2 540 4
1 430 5
11 300 6
13 230 7
10 200 8
where user_id = 11 is in the centre with 2 rows above and 2 below. I have tried nesting UNIONS and SELECT statements but nothing seems to work properly.
Here's a suggestion if you're on MySQL 8+:
Using common table expression (cte) then do a self join with condition of
user_id=11as base to get theRnkvalue of-2and+2.Demo fiddle
Since you're on older MySQL version, here's what I can suggest:
If you will only use
user_idas base, then the only part here you need to change is theSET @uid. The remaining queries are just fulfilling your condition of getting two positions above and below the rank retrieved according to theuser_id. The base query inSET @Rnkis the same as the base query for the last one. The idea is to assign@Rnkvariable withRnkposition ofuser_id=11then use it inWHEREcondition for the last query.I'm not aware if there's any online fiddle still using MySQL 5.1 but here's probably the closest version to it, MySQL 5.5 demo fiddle.