我在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
看一看在INNER JOIN,GROUP BY和SUM() – 2012-01-27 02:13:21