mysql sum和group通过给出错误的结果

时间:2011-07-14 17:37:21

标签: 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名用户得分。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

user_id表中找不到stats users表中的id。您甚至有2个用户具有相同的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 ?您的查询返回正确的结果。

{{1}}