只选择一行获取总行数

Get total row number while only selecting a single row

Related/similar 个问题:MySQL - Get row number on select, Select only partial result but get total number of rows

我目前有这个 table:

+----+--------------------+---------------+--------+
| id | accountId          | competitionId | rating |
+----+--------------------+---------------+--------+
|  1 | theidoftheaccount1 |            1  | 100    |
|  2 | theidoftheaccount2 |            3  | 90     |
|  3 | theidoftheaccount3 |            1  | 80     |
|  4 | theidoftheaccount4 |            1  | 50     |
+----+--------------------+---------------+--------+

我想用 accountId='theidoftheaccount3' 获取行,所以我调用通常的 SQL 语句 SELECT * FROM competitors WHERE competitionId='someotherid1' AND accountId='theidoftheaccount3 ' ORDER BY rating DESC 一切都很好。

问题: 现在我想知道我得到的行的行号,但只是在所有其他具有 competitionId='someotherid1' 的行中。 此行号将是同一比赛中所有其他参赛者中的参赛者 'rank'。

所以基本上在一天结束时我会回来:

+----+--------------------+---------------+--------+-----------+
| id | accountId          | competitionId | rating | rowNumber |
+----+--------------------+---------------+--------+-----------+
|  3 | theidoftheaccount3 |            1  | 80     | 2         |
+----+--------------------+---------------+--------+-----------+

如何做到这一点?

一种方法是在子查询中使用row_number()

select c.*
from (select c.*,
             rank() over (partition by competitionid order by rating desc) as ranking
      from competitors c
      where competitionId = 'someotherid1'
     ) c
where accountId = 'theidoftheaccount3';

编辑:

没有 window 功能的替代方案是:

select count(*) + 1 as ranking
from competitors c
where c.competitionId = 'someotherid1' and
      c.rating > (select c2.rating
                  from competitors c2
                  where c2.competitionid = c.competitionId and
                        c2.accountId = 'theidoftheaccount3' 
                 );

如果您的数据库不支持 window 函数,另一种方法是使用子查询:

select
    t.*,
    (
        select count(*) + 1
        from mytable t1
        where t1.competitionId = t.competitionId and t1.rating > t.rating
    ) row_num
from mytable t
where t.accountId = 'theidoftheaccount3' 

为了性能,您需要在列 (competitionId, rating) 上建立索引(在列 accountId 上建立另一个索引,但它可能已经存在,因为它看起来像 unique 列)。