mysql - 排名不按连载更新

标签 mysql sql sql-order-by

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

enter image description here

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

user_teams

用户 ID |匹配 ID |团队收入点

enter image description here

user_team_contests

用户 ID |用户团队 ID |比赛 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:

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/

相关文章:

php - 如何使用 php 加载 txt 文件并循环内容以查询数据库

使用 LAST_INSERT_ID() 在多个表上批量插入 MySQL

mysql - 排序依据在分组依据之前

sql - 为什么我不能使用 CASE 在 ORDER BY 中引用列别名?

mysql - 优化 MySQL - WHERE 和 ORDER BY 使用不同的列

java - MySQL Java 存储过程给出错误 "Parameter index of 1 is out of range"

使用来自另一个查询的关联的 PHP 查询

mysql - 如何过滤 MySQL 结果以在每个用户的基础上显示 LIMIT 1?

sql - 如何使用 t-sql 更新 xml 变量中的 xml 属性值?

mysql - 如何更新日期类型列?