如何根据信誉点来排名用户。
排除“ 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
答案 0 :(得分:1)
这基于您的代码:
SELECT id, rank FROM (
SELECT u.id, @rownum := @rownum +1 AS rank
FROM (
SELECT u.id
FROM users u
LEFT JOIN users_roles 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.registered_date ASC
) AS u
,(SELECT @rownum :=0 ) r
) AS t
WHERE id=3
请参见https://docs.spring.io/spring-javaconfig/docs/1.0.0.M4/reference/html/ch02s02.html
我在内部查询中包括了所有条件。
答案 1 :(得分:1)
我相信这可以满足您的需求
SELECT u.id, u.rank
FROM (SELECT u.id, (@rownum := @rownum + 1) AS rank
FROM users u CROSS JOIN
(SELECT @rownum := 0 ) r
WHERE NOT EXISTS (SELECT 1
FROM users_role ur JOIN
roles r
ON r.id = ur.role_id
WHERE ur.user_id = u.id AND
r.key_role NOT IN ('super_admin', 'staff')
)
ORDER BY u.reputation DESC, u.register_date ASC
) u
WHERE u.id = 3;
尤其是,具有多个角色的用户不会影响排名。
请注意,在较新版本的MySQL中,变量不能与ORDER BY
配合使用,因此您需要一个附加的子查询。在最新版本中,您只需使用窗口功能即可。