MYSQL JOIN同一个表+ COUNT来确定排名

时间:2017-04-24 15:15:56

标签: mysql join

我有一个包含多个userIds的表RANKINGS,与genreId相关联,以及与该类型相关的排名。

作为基准测试,我将使用userId = 30520,但该表包含大量记录。

userId    genreId    ranking
30520     0          135
30520     13         91
30520     24         163

手动计算userId的位置很容易,例如最后一条记录:

SELECT COUNT(ranking) as position
FROM rankings
WHERE genreId = 24
AND ranking >= 163
ORDER BY ranking DESC

通过这种手动方法,我得到:

userId    genreId    ranking    position
30520     0          135        5
30520     13         91         17
30520     24         163        7

但我无法想象如何通过一个查询实现这一目标。我的尝试:

SELECT userId, a.genreId, COUNT(a.ranking) as position,
FROM rankings a
LEFT JOIN 
(
    SELECT genreId, ranking
    FROM rankings
    WHERE userId = 30520
) b
ON a.genreId = b.genreId
AND a.ranking >= b.ranking
ORDER BY a.ranking DESC

我只有一行:

userId    genreId    position
30520     0          3741

感谢您的任何提示!

1 个答案:

答案 0 :(得分:0)

只需将分组添加到您的查询中:

SELECT userId, a.genreId, COUNT(a.ranking) as position
FROM rankings a
LEFT JOIN 
(
    SELECT genreId, ranking
    FROM rankings
    WHERE userId = 30520
) b
ON a.genreId = b.genreId
AND a.ranking >= b.ranking
GROUP BY genreId
ORDER BY a.ranking DESC