2011-07-17 77 views
1

我想下面的查詢顯示所有我在用戶頁面的用戶的...問題上的MySQL INNER JOIN

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

爲什麼'user1'和'user2'都有'id'等於'1'? – bernie

回答

2

你需要使用GROUP BY,以便在不同的用戶分割得分的總和,進一步,如果你使用LEFT JOIN,那麼即使在stats表中沒有行,您也一定會爲每個用戶實例獲得一行(然後,使用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 

這不是測試

+0

你好,謝謝你的答覆,它仍然返回3行而不是4.我們有4個用戶在用戶表中,如果我們做簡單的SELECT * from用戶,我們得到4個用戶,但是使用INNER JOIN給出3行/用戶。 – seoppc

+0

,如果某些用戶沒有統計數據,則可以使用總數爲COALESCE的統計數據的左連接。 – regilero

+0

@Daniele實際上'由u.id'組應該足夠了:) – Karolis