Select a range using MySQL ORDER BY
-
13-06-2021 - |
سؤال
So I have this game database, where I have several users with fields, id, name, points
I need a rank table for a specific user where its position can be seen in relation to the amount of points, there is room for 8 positions in the table, so I was looking for a way to do the following:
if I do SELECT * FROM users WHERE id = {user_id} ORDER By points
Select the 4 results before and the 3 results after this id. is there a query to do this? the result should look like:
---------------------
|id |name |points|
---------------------
| 52 |name1 | 10 |
---------------------
| 23 |name1 | 09 |
---------------------
| 93 |name1 | 08 |
---------------------
| 12 |name1 | 07 |
---------------------
| 43 |queried_name1 | 06 |
---------------------
| 67 |name1 | 05 |
---------------------
| 32 |name1 | 04 |
---------------------
| 91 |name1 | 03 |
---------------------
I was trying to make this by software but it is pretty slow to iterate trough all the results. Thanks for your help!
المحلول
Like that, I would say, for the above results:
SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3;
For the below results:
SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4;
So, with a big union, it would give:
SELECT * FROM (SELECT * FROM users WHERE points > (SELECT points FROM users WHERE id = {user_id}) ORDER By points ASC LIMIT 3 ) a
UNION
SELECT * FROM users WHERE id = {user_id}
UNION
SELECT * FROM ( SELECT * FROM users WHERE points < (SELECT points FROM users WHERE id = {user_id}) ORDER By points DESC LIMIT 4 ) b
نصائح أخرى
You can use this query -
SELECT id, name, points FROM (
SELECT u.*, @r:=@r+1 rank, @pos:=IF(@pos = 0 AND name = 'queried_name1', @r, @pos)
FROM users u,
(SELECT @r:=0, @pos:=0) t
ORDER BY points DESC
) t
WHERE rank BETWEEN @pos - 4 AND @pos + 3
It ranks table by points, finds a record with name = 'queried_name1', and selects some rows before and after the found record.