查询mysql返回错误的SUM

时间:2014-05-21 14:50:42

标签: mysql sql database

下午好朋友,

我正在开发一个应用程序,我有一个页面显示“房间”顶部。我想得到一些“房间”内所有用户的应用点数总和。

我已完成此查询:

SELECT rooms.id, rooms.name, SUM(users.points)
FROM users, room_players, rooms
WHERE users.id = room_players.user AND room_players.room = rooms.id

这会返回所有房间内所有用户的积分总和,我希望按房间总计所有用户的应用点数。

有人可以帮我找到此查询中的错误吗?

非常感谢。

3 个答案:

答案 0 :(得分:3)

可能需要GROUP BY子句

SELECT rooms.id, rooms.name, SUM(users.points) 
FROM users, room_players, rooms 
WHERE users.id = room_players.user AND room_players.room = rooms.id
GROUP BY  rooms.id, rooms.name

使用更现代的联接: -

SELECT rooms.id, rooms.name, SUM(users.points) 
FROM users
INNER JOIN room_players ON users.id = room_players.user
INNER JOIN rooms ON room_players.room = rooms.id
GROUP BY  rooms.id, rooms.name

答案 1 :(得分:0)

使用GROUP BY room.id按房间分组SUM

答案 2 :(得分:0)

您应该使用联接和分组:

Select 
   c.id,c.name,sum(a.points) from users a
Inner join room_players b
   On (a.id=b.user)
Inner join rooms c
   On (b.room=c.id)
Group by c.id,c.name