MySQL - select rank for users in a score table(MySQL - 在分数表中为用户选择排名)
问题描述
我有一个具有这种结构的user_score"表:
I've got a 'user_score' table with that structure:
|id|user_id|group_id|score| timestamp |
| 1| 1| 1| 500| 2013-02-24 18:00:00|
| 2| 2| 1| 200| 2013-02-24 18:01:50|
| 3| 1| 2| 100| 2013-02-24 18:06:00|
| 4| 1| 1| 6000| 2013-02-24 18:07:30|
我需要做的是从该表中选择来自确切组的所有用户.选择他们在该组中的实际(根据时间戳)得分和排名.
What I need to do is to select all users from that table which are from the exact group. Select their actual (according to timestamp) score in that group and their rank.
我所拥有的是(在 Jocachin 发表评论后,我发现我自己的查询没有按预期工作,对不起):
SELECT user_id, score, @curRank := @curRank + 1 AS rank
FROM (
SELECT *
FROM (
SELECT * FROM `user_score`
WHERE `group_id` = 1
ORDER BY `timestamp` DESC
) AS sub2
GROUP BY `user_id`
) AS sub, (SELECT @curRank := 0) r
ORDER BY `rank`
示例数据和 group_id = 1 的预期结果:
Expected result for example data and group_id = 1:
|user_id|score|rank|
| 1| 6000| 1|
| 2| 200| 2|
但是 MySQL 子选择有点问题,请问您还有其他解决方案吗?
But MySQL subselects are a bit problematic, do you see any other solution, please?
稍后我可能需要获得组中单个用户的排名.我现在迷路了.
I'll probably need to get the rank od single user in the group later. I am lost at the moment.
推荐答案
虽然我不确定有问题"在这种情况下是什么意思,但这里将查询重写为普通的 LEFT JOIN一个子查询只是为了在最后获得排名(ORDER BY需要在排名之前完成);
Although I'm not sure what "problematic" means in this context, here is the query rewritten as a plain LEFT JOIN with a subquery just to get the ranking right at the end (the ORDER BY needs to be done before the ranking);
SELECT user_id, score, @rank := @rank + 1 AS rank FROM
(
SELECT u.user_id, u.score
FROM user_score u
LEFT JOIN user_score u2
ON u.user_id=u2.user_id
AND u.`timestamp` < u2.`timestamp`
WHERE u2.`timestamp` IS NULL
ORDER BY u.score DESC
) zz, (SELECT @rank := 0) z;
一个用于测试的 SQLfiddle.
要考虑 group_id,您需要稍微扩展查询;
To take group_id into account, you'll need to extend the query somewhat;
SELECT user_id, score, @rank := @rank + 1 AS rank FROM
(
SELECT u.user_id, u.score
FROM user_score u
LEFT JOIN user_score u2
ON u.user_id=u2.user_id
AND u.group_id = u2.group_id -- u and u2 have the same group
AND u.`timestamp` < u2.`timestamp`
WHERE u2.`timestamp` IS NULL
AND u.group_id = 1 -- ...and that group is group 1
ORDER BY u.score DESC
) zz, (SELECT @rank := 0) z;
另一个 SQLfiddle.
这篇关于MySQL - 在分数表中为用户选择排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL - 在分数表中为用户选择排名
基础教程推荐
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
