SQL根据信誉分数排名

时间:2019-03-04 18:40:11

标签: mysql

如何通过信誉点获得用户等级排序。
“ super_admin”和“ staff”角色不应在此排名。

我的查询
当我提出要求(包括所有用户)时,排名很好,但 当我提出请求时,排除具有“ super_admin”和“ staff”角色的用户时,排名是错误的

SELECT u.id, u.rank 
FROM (
      SELECT u.id, @rownum := @rownum +1 AS rank
      FROM users u, (SELECT @rownum :=0 ) r
      ORDER BY u.reputation DESC, u.register_date ASC
     ) AS u
LEFT JOIN users_role ur ON ur.user_id = u.id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE r.key_role NOT IN ('super_admin','staff')
AND u.id=3

表格:

users table

ID    REPUTATION     REGISTERED_DATE
1     6000           2018-05-20 14:15:10
2     20             2018-05-22 14:15:10
3     2000           2018-05-25 14:15:10
4     350            2018-05-27 14:15:10
5     14             2018-05-27 19:15:10
6     0              2018-05-28 14:15:10
7     584            2018-05-29 14:15:10
8     54             2018-05-30 14:15:10


users_roles table

ID    USER_ID        ROLE_ID
1     1              1
2     2              2
3     3              3
4     4              3
5     5              3
6     6              3
7     7              3
8     8              3


roles table

ID    NAME              KEY_ROLE
1     Super Admin       super_admin
2     Staff             staff
3     Registered user   registered_user

1 个答案:

答案 0 :(得分:1)

将排序移到最外面的查询:

(已更新)

SELECT u.id, @rownum := @rownum +1 AS rank
FROM users u, (SELECT @rownum :=0 ) r
LEFT JOIN users_role ur ON ur.user_id = u.id
LEFT JOIN roles r ON r.id = ur.role_id
WHERE r.key_role NOT IN ('super_admin','staff')
ORDER BY u.reputation DESC,  u.register_date ASC