gpt4 book ai didi

mysql - 排名不按连载更新

转载 作者:行者123 更新时间:2023-11-29 01:48:44 25 4
gpt4 key购买 nike

我想按排序顺序更新我的排名列。但它不是那样排序的。

enter image description here

我希望第一行的排名为 1,第二行的排名为 2。

user_teams

用户ID |匹配ID | team_earning_point

enter image description here

user_team_contests

user_id |user_team_id |contest_id

enter image description here

在两个表中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 before 分配变量:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com