2012-12-04 198 views
0

我試圖按照此示例:MySQL - ranking by count() and GROUP BY但我的rank列一直返回nil。MySQL - GROUP BY返回nil的COUNT COUNT

這裏是我的查詢:

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的每一行。

回答

0

你必須開始增加它之前,你的rownum初始化爲0,或者通過

SET @rownum := 0; 

查詢之前,或單獨SELECT條款後,你的第一個FROM

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