2011-07-14 45 views
1

我使用下面的表格......MySQL的總和和組給予錯誤的結果

stats (id, game, user_id, rank, score, dnt) 
teams(id, name, dnt) 
users(id, username, email, team_id, dnt) 

我要搶根據統計排名前10位的高得分的球隊(球隊總比分被其使用者對總成績)

爲統計樣本數據...

| id | game | user_id | rank | score | dnt | 
+----+------+---------+-------+------+-----+ 
| 1 | test | 5  | 2 | 2200 | 
+--------+----------+----------+-----+-----+ 
| 2 | test | 3  | 1 | 2500 | 
+--------+----------+----------+-----+-----+ 

| id | name | dnt | 
+----+-------+-----+ 
| 1 | team1 |  | 
+----+-------+-----+ 
| 2 | team2 |  | 
+----+-------+-----+ 

用戶

| id | username | email | team_id | 
+----+----------+-------+---------+ 
| 1 | user1 |  | 1  | 
+----+----------+-------+---------+ 
| 1 | user2 |  | 2  | 
+----+----------+-------+---------+ 

,我想下面的SQL查詢...

SELECT t.name as team_name, sum(s.score) as total_score 
     FROM teams t 
     JOIN users u ON u.team_id = t.id 
     JOIN stats s ON s.user_id = u.id 
     GROUP BY team_name ORDER BY total_score DESC 

但上面的查詢將返回0行,即使我想你幫忙寫TP往上頂10用戶得分。

感謝您的幫助。

+0

其他表的樣本數據請。 – Jacob

+0

@cularis添加了更多示例數據。謝謝。 – seoppc

回答

2

您的user_idstats表無處可在您的users表中找到。你甚至有2個用戶使用相同的id?您的查詢返回正確的結果。

SELECT t.name as team_name, sum(s.score) as total_score 
FROM teams t 
INNER JOIN users u 
    ON u.team_id = t.id 
INNER JOIN stats s 
    ON s.user_id = u.id 
GROUP BY team_name 
ORDER BY total_score DESC 
LIMIT 10 
+0

感謝您能幫助我們如何才能獲得高分的前10名用戶。 – seoppc

+0

你走了。顯然只有在表格中有正確的數據時纔有效。 – Jacob

+0

感謝您的幫助 – seoppc