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 - 在分数表中为用户选择排名
基础教程推荐
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
