0

我正在尝试遵循以下示例:MySQL - 按 count() 和 GROUP BY 排名,但我的rank列一直返回 nil。

这是我的查询:

SELECT 
  @rownum := @rownum+1 AS rank,
  q.id, 
  q.Name, 
  q.count 
FROM
(SELECT
    Accounts.id,
    Accounts.Name,
    COUNT(Accounts.Name) AS count
FROM
    player_to_team_histories
        INNER JOIN
    team_histories ON team_histories.id = player_to_team_histories.team_history_id
        INNER JOIN
    teams ON teams.id = team_histories.team_id
        INNER JOIN
    accounts ON accounts.id = teams.account_id
WHERE
    accounts.AccountTypeId = 1 AND player_id IN (SELECT 
        player_id
    FROM
        player_to_team_histories
    WHERE
        player_to_team_histories.not_valid IS NULL AND team_history_id = (SELECT 
            team_history_id
        FROM
            player_to_team_histories
                INNER JOIN
            team_histories ON team_histories.id = player_to_team_histories.team_history_id
        WHERE
            player_to_team_histories.id = 574651))
GROUP BY Accounts.Name
ORDER BY count DESC)q

除了rank按预期返回之外的每一列,并且每行都rank返回null

4

1 回答 1

0

在开始增加它之前,您必须将 rownum 初始化为 0,或者通过

SET @rownum := 0; 

在查询之前,或者在您的第一个之后的单独SELECT子句FROM

SELECT ...
FROM
(SELECT @rownum := 0 ) counter, 
(SELECT
 ... )
于 2012-12-04T19:39:27.310 回答