关于mysql INNER JOIN的问题

时间:2011-07-17 18:47:46

标签: mysql

我正在尝试关注查询以在用户页面显示我的所有用户...

SELECT u.id, u.username, u.email, u.active, u.admin,
u.team_id, t.name AS team_name, sum( s.score ) AS total_score
FROM users u
INNER JOIN teams t ON u.team_id = t.id
INNER JOIN stats s ON u.id = s.user_id

我的用户表中有4个用户,我想列出所有用户,但如果我使用INNER JOIN,则只返回1行。检查数据结构如下......

| 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       |
+----+----------+-------+---------+

1 个答案:

答案 0 :(得分:2)

您需要使用GROUP BY才能将得分的总和分配给不同的用户,如果使用LEFT JOIN则需要更多,那么即使它已经确定每个用户实例都有一行统计信息表格中没有行(然后,使用COALESCE作为regilero建议,总和将为0

类似的东西:

SELECT u.id, u.username, u.email, u.active, u.admin,
u.team_id, t.name AS team_name, sum( COALESCE(s.score) ) AS total_score
FROM users u
LEFT JOIN teams t ON u.team_id = t.id
LEFT JOIN stats s ON u.id = s.user_id
GROUP BY u.id, u.username, u.email, u.active, u.admin,
u.team_id, t.name

未经测试

相关问题