如何创建排名系统

时间:2017-07-06 12:33:04

标签: php mysql

我在视图方面有一个user_score列的用户表我希望显示每个用户的排名和分数以及之前/之后的2个人。

如何使用MySQL或PHP以最短的执行时间实现此功能?

示例

+-----------+------------+
| User_id   | Score      |
+-----------+------------+
| 1         | 12258      |
| 2         | 112        |
| 3         | 9678       |
| 4         | 689206     |
| 5         | 1868       |
+-----------+------------+

例如我的user_id = 3。我想像这样展示

                    you
                   9678    

 user befor you               user after you
    12258                            1868       

1 个答案:

答案 0 :(得分:1)

如果您只想使用MySQL:

SELECT usr。user_id,(SELECT usr1。user_score FROM user usr1 WHERE usr。user_score> = usr1。user_score AND usr。{ {1}}!= usr1。user_id ORDER BY usr1。user_id DESC LIMIT 1)AS user_score,usr。user_before_you AS user_score,(SELECT usr1 。you FROM user_score usr1 WHERE usr。user< = usr1。user_score AND usr。user_score!= usr1。user_id ORDER BY usr1。user_id ASC LIMIT 1)AS user_score FROM user_after_you usr WHERE 1