开发者

mysql sum and group by giving wrong results

开发者 https://www.devze.com 2023-03-20 14:46 出处:网络
I am using following tables... stats (id, game, user_id, rank, score, dnt) teams(id, name, dnt) users(id, username, email, team_id, dnt)

I am using following tables...

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

I want to grab top 10 high scorer teams based on stats(team total score gets calculated on total score by its users)

sample data for stats...

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

teams

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

users

| id | username | email | team_id |
+----+----------+-------+---------+
|  1 | user1    |       | 1       |
+----+----------+-------+--开发者_如何学Go-------+
|  1 | user2    |       | 2       |
+----+----------+-------+---------+

And i am trying following sql query...

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

But above query is returning 0 rows, even i want your help tp write up top 10 users score.

Thanks for help.


Your user_id in stats table is nowhere to be found in your users table. You even have 2 users with the same id? Your query returns the correct result.

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

精彩评论

暂无评论...
验证码 换一张
取 消