简体   繁体   English

MySQL-通过返回nil从GROUP BY排名COUNT

[英]MySQL - Rank COUNT from GROUP BY returning nil

I'm trying to follow this example: MySQL - ranking by count() and GROUP BY but my rank column keeps returning nil. 我正在尝试遵循以下示例: MySQL-按count()和GROUP BY进行排名,但我的rank列始终返回nil。

Here's my query: 这是我的查询:

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

Every column except rank is returning as expected, and rank is returning null for every row. rank之外的所有列均按预期返回,并且rank对每一行返回null

You have to initialize your rownum to 0 before starting to increment it, either by 您必须先将rownum初始化为0,然后才能开始递增它,方法是

SET @rownum := 0; 

before the query, or by a separate SELECT clause after your first FROM : 在查询之前,或在您的第一个FROM后面通过单独的SELECT子句:

SELECT ...
FROM
(SELECT @rownum := 0 ) counter, 
(SELECT
 ... )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM