2012-01-27 59 views
1

我在MySQL上有兩個表,結構如下:一對多關係中有多少行?

用戶: ID |名稱

帳戶: ID |用戶ID |金額

我需要一個查詢來獲取每個用戶的總帳戶,並在結果中包含用戶名。有沒有辦法做到這一點?我已經在from子句中嘗試了子查詢,並且我不知道如何使用連接來實現此目的,但是我懷疑這是否可能是解決方案...任何想法?

這裏的樣本數據和示例輸出我假裝獲得:

Users 
1 | 'John' 
2 | 'Peter' 

Accounts 
1 | 1 | 1000 
2 | 1 | 2000 
3 | 2 | 1500 

query: 
'John' | 2 <- there are 2 accounts for user 'John' 
'Peter' | 1 <- there is only 1 account for user 'Peter' 

而且,如果我想在我的結果更多的彙總數據?說...總金額。例如:

another query: 
'John' | 2 | 3000 <- 2 accounts for John, which sums 3000 
'Peter' | 1 | 1500 <- 1 account for Peter, which sums 1500 
+0

看一看在INNER JOIN,GROUP BY和SUM() – 2012-01-27 02:13:21

回答

2

這裏有一個查詢來獲取用戶的名字和他們的帳戶數:

SELECT u.name, COUNT(a.id) AS numAccounts 
FROM Users u 
LEFT JOIN Accounts a ON u.id=a.userid 
GROUP BY u.id; 

要得到量列的總和,你可以這樣做:

SELECT u.name, COUNT(a.id) AS numAccounts, SUM(u.amount) AS totalAmount 
FROM Users u 
LEFT JOIN Accounts a ON u.id=a.userid 
GROUP BY u.id; 
2
select u.name, count(a.id) as numAccounts 
from 
users as u, accounts as a 
where u.id = a.userid 
group by u.id 


select u.name, count(a.id) as numAccounts, sum(a.amount) as totalAmount 
from 
users as u, accounts as a 
where u.id = a.userid 
group by u.id 

編輯:請注意,如果用戶沒有帳戶,他們將不會出現在這裏,您將需要一個左連接像約拿的查詢。

+0

謝謝!似乎左邊加入的解決方案是唯一的;) – 2012-01-27 02:33:25