排名未按序列更新

时间:2019-05-04 12:54:30

标签: mysql sql sql-order-by

我想通过排序来更新我的等级列。但是它不是那样排序的。

enter image description here

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

user_teams

user_id | match_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

在哪里更改我的代码以获得准确的结果?

1 个答案:

答案 0 :(得分:3)

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