我想按排序顺序更新我的排名列。但它并不是这样排序的。
我希望第一行的排名为 1,第二行的排名为 2。
user_teams
用户 ID |匹配 ID |团队收入点
user_team_contests
用户 ID |用户团队 ID |比赛 ID
在两个表中Id都是主键
这是我的sql代码:
Set @a=0;
SELECT u_t.id,u_t.match_id,u_t.team_earning_point, @a:=@a+1 as ranking
FROM user_teams AS u_t, user_team_contests as u_t_c
WHERE u_t_c.contest_id=21 AND u_t.id = u_t_c.user_team_id
ORDER BY u_t.team_earning_point DESC, u_t_c.created_at ASC
在哪里更改我的代码以获得准确的结果?
最佳答案
MySQL 中的变量非常挑剔。您应该在分配变量之前order by
:
SELECT ut.*, (@rn := @rn + 1) as ranking
FROM (SELECT u_t.id u_t.match_id, u_t.team_earning_point
FROM user_teams u_t JOIN
user_team_contests u_t_c
ON u_t.id = u_t_c.user_team_id
WHERE u_t_c.contest_id = 21
ORDER BY u_t.team_earning_point DESC, u_t_c.created_at ASC
) ut CROSS JOIN
(SELECT @rn := 0) params;
您会注意到我还修复了您过时的连接语法。您应该始终使用 JOIN
/ON
来表达连接。
当然,在 MySQL 8+ 中,您只需使用:
row_number() over (partition by u_t_c.contest_id order by u_t.team_earning_point DESC, u_t_c.created_at) as ranking
关于mysql - 排名不按连载更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55982721/