简体   繁体   中英

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.

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.

You have to initialize your rownum to 0 before starting to increment it, either by

SET @rownum := 0; 

before the query, or by a separate SELECT clause after your first FROM :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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