使用SQL查询获取团队排名


Getting team rank with SQL query

我有一个SQL查询,用于根据团队的"点"获取数据库中团队的排名号。

SELECT id, points, team_name, FIND_IN_SET( points, (
    SELECT GROUP_CONCAT( points
    ORDER BY points DESC )
    FROM teams )
    ) AS rank
    FROM teams
    WHERE id = ?
    LIMIT 1

我遇到的问题是,在两支球队得分相同的情况下,比如说有两支球队,每支球队都有"0"分。查询返回两个团队的排名"1"。

我希望得分相同的球队中,id较低的球队排名较高。

例如,team1和team2都有"5"分。我希望id较低的球队排名第一。

如何更改我的查询以执行此操作?

感谢

您使用的方法在MySQL中的适用性有限,因为它取决于group_concat()中中间子字符串的长度。但是,您可以为此目的对其进行修改:

SELECT id, points, team_name,
       FIND_IN_SET(CONCAT(points, ':', id),
                   (SELECT GROUP_CONCAT(points, ':', id ORDER BY points DESC, id )
                    FROM teams
                   )
                  ) AS rank
FROM teams
WHERE id = ?
LIMIT 1;

更好的方法是:

select id, points, team_name,
       (select count(*)
        from teams t2
        where t2.points > t.points or
              (t2.points = t.points and t2.id <= t.id)
       ) as rank
from teams t
where id = ?;