我在MySQL上有两个表,结构如下:
用户: id |名称
帐户: id | userid |量
我需要一个查询来获取每个用户的总帐户,结果中的用户名也是如此。有没有办法实现这个目标?我在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 :(得分: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
编辑:请注意,如果用户没有帐户,则他们不会在此处显示,并且您需要像Jonah的查询一样的左连接。
答案 1 :(得分: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;