2011-07-14 32 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