Mysql - Fetch 5 rows above and under user (ranking) -


i have table:

r_user  | r_points | -------------------- user1   | 12       | user2   | 124      | user3   | 34       | user4   | 35       | user5   | 57       | user6   | 3        | user7   | 452      | user8   | 8        | user9   | 12       | user-c  | 0        | user-b  | 0        | user-a  | 0        | 

lets want fetch ranking user6. want 5 users above , below entry ordered r_points , next r_user asc, users equal points ( user-c, user-b, user-a ) sorted asc ( user-a, user-b... ).

if there aren't 5 users above or underneath, difference should put opposite. if user6 4 bottom, want 6 users fetched above. count of 10 users.

that result, have:

r_user  | r_points | -------------------- user5   | 57       | user4   | 35       | user3   | 34       | user9   | 12       | user1   | 12       | -> in direction order other way round user8   | 8        | user6   | 3        | --> thats user id <-- user-a  | 0        | user-b  | 0        | user-c  | 0        | 

i have no idea, how that, since table has r_user pk , no ai-id.

thank you

edit:

that's version of it. version not fetching more users above/below if user on 3rd bottom. works if there 5 rows underneath , above. that's not want.

( select r_user, r_points ranking  r_points >= ( select r_points ranking r_user = 'user6' ) order r_points asc limit 5 ) union distinct ( select r_user, r_points ranking  r_points <= ( select r_points ranking r_user = 'user6' ) order r_points desc limit 6 ) order r_points desc, r_user asc 

you wrote have no unique id, in fiddle user hard coded line if(t.r_user = 'user2'. change user have change value.

hope helpful you:

http://sqlfiddle.com/#!9/d2329/31

select * (   select      t.*,     if(@idx null, @idx:=1, @idx:=@idx+1) idx,     if(t.r_user = 'user2',@median:=r_points, if(@start null, @start:=@idx, if(@after null, @start:=@idx, null))),     if(@median null, if(@before null,@before:=1, @before:=@before+1) ,     if(@after null ,@after:=0, @after:=@after+1))     (     select *      table1      order r_points desc     ) t   ) t2  if(1+@before+@after<=10, true,           if(@before<=5, t2.idx >= 0 , t2.idx <= @start+5+(5-@before),              if(@after<=4, t2.idx >= @start-4-(4-@after),                 t2.idx >= @start-4 , t2.idx <= @start+5              )           )         ); 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -